Manu
Manu

Reputation: 11

Please specify the reason for the given output in following java code

Why does the following Java code print the output 2342245.75000000 instead of 2342245.80000000?

float n=2342245.8f;
System.out.printf("%.8f\n",n);

Output:

2342245.75000000

Upvotes: 1

Views: 78

Answers (1)

kaya3
kaya3

Reputation: 51037

The answer is that 2342245.8f == 2342245.75f. They are the same floating-point number; just two different decimal representations. The precision of floats at that magnitude is such that only two bits are used for the fractional part; so the next float below it is 2342245.5f, and the next one above is 2342246.0f. There are no other floats in between those two numbers.

The difference in what you see on the screen is purely string formatting: 2342245.8 is the shortest string which will be rounded to that floating point number, so that's what String.valueOf returns, and hence that's what you'll see if you just do System.out.println. But 2342245.75 is a more accurate decimal representation, which is used by the printf method because you told that method to use more decimal places.

Upvotes: 2

Related Questions