Precision lost in float value using java

后端 未结 5 1126
醉酒成梦
醉酒成梦 2020-12-03 16:15

Given below the test code and its output. When I get float value from number value, precision is lost.. Can anyone tell me why this behaviour and also how to handle this?

5条回答
  •  醉酒成梦
    2020-12-03 17:01

    Decimal literals like the one you have typed default to type double, not float. java.lang.Number also uses doubles by default. If you were to replace that with java.lang.Number numberVal = 676543.21f; I would expect the same level of precision loss from both. Alternatively, replace float floatVal = numberVal.floatValue(); with double doubleVal = numberVal.doubleValue(); In order not to lose precision.

    EDIT, as an example, try running:

    Number num = 676543.21;
    System.out.println(num); //676543.21
    System.out.println(num.doubleValue()); //676543.21
    System.out.println(num.floatValue()); //676543.2 <= loses the precision
    

    to see the difference in precision of the types

    Float.MAX_VALUE returns the largest value that a float can ever hold. any higher will overflow. If you look carefully, you'll see an 'E' in its textual representation. This is standard index form, that 'E' means "multiply by 10 to the power of whatever number follows the E" (or in java-speak *pow(10, numberAfterE))

提交回复
热议问题