Search code examples
javafloating-point-conversion

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?


Solution

  • 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.