Reputation: 425
Please have a look at the below code:
float num = 72000000.69f;
System.out.println(String.format("%.2f", num));
Output: 72000000.00
I am loosing the precision. I have tried by converting to float to BigDecimal and then printing the values, but it doesn't help.
Any way to preserve the precision?
Upvotes: 1
Views: 128
Reputation: 135992
Try this test
System.out.println(72000000.69f == 72000000f);
it prints
true
this means .69 is simply cut off due to float's low precision, it's simply not there, you cant restore it by any means.
Upvotes: 0
Reputation: 17422
Use BigDecimal, floating types don't store all your number the way you think
Upvotes: 0
Reputation: 7668
BigDecimal num = new BigDecimal("72000000.69");
System.out.println(num);
Output:
72000000.69
Upvotes: 2
Reputation: 5722
A float has seven digits of precision. You got your seven digits.
If you want greater precision, use a double instead.
Upvotes: 5