sapan
sapan

Reputation: 150

java float conversion to string giving different result

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

Upvotes: 4

Views: 263

Answers (3)

Little Santi
Little Santi

Reputation: 8813

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.

Upvotes: 2

Paul Boddington
Paul Boddington

Reputation: 37655

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.

Upvotes: 2

kwz
kwz

Reputation: 701

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)

Upvotes: 0

Related Questions