Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float value parsing in java

When I am doing this

value = Float.parseFloat("5555998.558f");

System.out.println("Value: " + value);

It gives me result 5555998.5 rather than 5555998.558 I am using the variable value for some calculation. And I need the exact value i.e. 5555998.558

How to overcome this?

like image 771
Biswadip Dey Avatar asked May 31 '26 01:05

Biswadip Dey


2 Answers

The float value at that high value has a precision of only 0.5, so Java parsed it to the closest float value it could = 5555998.5, and that's what was printed.

To see the difference between the 2 closest values at that magnitude, use Math.ulp (unit in the last place):

String s = "5555998.558f";
float value = Float.parseFloat(s);
System.out.println(value);
System.out.println(Math.ulp(value));

This prints

5555998.5
0.5

You can use a double which has much better precision:

double d = Double.parseDouble(s);
System.out.println(d);
System.out.println(Math.ulp(d));

This prints

5555998.558
9.313225746154785E-10

Interestingly, Double.parseDouble doesn't seem to mind the f on the end. Double.parseDouble converts the String into a double "as performed by the valueOf method of class Double". And Double.valueOf states:

FloatValue:

  • Signopt NaN

  • Signopt Infinity

  • Signopt FloatingPointLiteral

  • Signopt HexFloatingPointLiteral

  • SignedInteger

This method will take a String as if it were a Java numeric literal, which Java supports with a f on the end to indicate a floating-point literal.

like image 59
rgettman Avatar answered Jun 01 '26 14:06

rgettman


BigDecimal is probably your best bet for exact decimal representations.

BigDecimal value = new BigDecimal("5555998.558");

It's immutable, so every operation you do to it will result in you creating a new BigDecimal instance, but its precision is also likely what you need.

like image 25
Makoto Avatar answered Jun 01 '26 16:06

Makoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!