4

why below java code prints different value (decimal part) of same float variable?

public static void main(String[] args) {
    float f = 2001797.11f;
    System.out.println(String.format("%013.2f", f));
    System.out.println(Float.toString(f));
    System.out.println(String.format("%018.5f", f));
}

Output:

0002001797.13
2001797.1
000002001797.12500
Konamiman
  • 49,681
  • 17
  • 108
  • 138
sapan
  • 150
  • 7
  • I thinks it may be some rounding off behind the screen but want to know why this behavior when i am just trying to print the same variable. None of them giving the actual value – sapan Aug 04 '15 at 12:15
  • `2001797.11` is too large to be represented precisely to float precision – phuclv Aug 04 '15 at 12:45

3 Answers3

2

The confusion stems from the line float f = 2001797.11f;. The closest float to the mathematical value "2001797.11" is actually 2001797.125. You can see this by doing

System.out.println(new BigDecimal(2001797.11f));

So, f is actually 2001797.125 and the 2 uses of String.format have rounded correctly.

So why doesn't Float.toString(f) produce "2001797.125"? It's because Float.toString only displays enough decimal places in order to distinguish the value from other floats. In this case, just displaying the 1 after the decimal place is enough.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
2

You must consider that float and double types handle floating point numbers: This means that they have to distribute its 32 or 64 bits between the integer and the decimal part.

And so: The most digits in the integer part, the most bits will be dedicated to them, and the less bits to the decimal part. So, the decimal part will be less accurate.

The problem you are suffering comes from two facts:

  • Too much digits in the integer part.
  • Using float.

If you need more precission (according to the scale of values your program must handle), you should migrate to double. And if you want infinite precission, to BigDecimal.

Little Santi
  • 8,563
  • 2
  • 18
  • 46
0

String.format use explicit formatting rules while Float.toString(float n) use the algorithm which is described in documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#toString(float)

kwz
  • 701
  • 6
  • 13