I need avoid round number when casting a float to string, I need the number is exactly the same.
In this moment if I make this:
String value = String.valueOf(1234567.99);
The the value = 1234568.0 ,so I need the value = 1234567.99 after casting.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
1234567.99can’t be exactly represented as a float. The nearest float is actually equal to 1234568.If you want more precision, you can use a double:
1234567.99dwill do what you expect.You can run this simple test to check it (it is in Java but easily transposable on android by replacing the
println):prints:
Note:
String.valueOf(double)does round the double to another representation, with less decimals, of the same double. In other words, as you see above1234567.99dcan’t be represented as a double and the nearest double is1234567.98999999999068677425384521484375. ButString.valueOffigures it out and uses the first representation of that double (with only 2 decimals) since they are effectively the same double according to the specifications of the language.