Ayushi
Ayushi

Reputation: 425

Losing precision while printing float

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

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

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

morgano
morgano

Reputation: 17422

Use BigDecimal, floating types don't store all your number the way you think

Upvotes: 0

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7668

BigDecimal num = new BigDecimal("72000000.69");
System.out.println(num);

Output:

72000000.69

Upvotes: 2

Curt
Curt

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

Related Questions