Convert java float to string giving different results

why below java code prints another value (decimal part) of the 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 
+4
source share
3 answers

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

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

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

So why does Float.toString(f) not produce "2001797.125" ? This is because Float.toString displays enough decimal places to distinguish the value from other float s. In this case, just displaying 1 after the decimal place is enough.

+2
source

You should keep in mind that the types float and double handle floating point numbers: this means that they must allocate their 32 or 64 bits between the integer and the decimal part.

And so: most digits in the integer part, most bits will be devoted to them, and the less bits - the decimal part. Thus, the decimal part will be less accurate.

The problem you suffer comes from two facts:

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

If you need additional refueling (in accordance with the scale of values ​​that your program should handle), you should switch to double . And if you want endless precession, BigDecimal .

+2
source

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

0
source

All Articles