What's the right way to parseFloat in Java

后端 未结 7 1759
[愿得一人]
[愿得一人] 2021-01-12 01:52

I notice some issues with the Java float precision

       Float.parseFloat(\"0.0065\") - 0.001  // 0.0055000000134110451
       new Float(\"0.027\") - 0.001          


        
7条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 02:30

    You're getting the right results. There is no such float as 0.027 exactly, nor is there such a double. You will always get these errors if you use float or double.

    float and double are stored as binary fractions: something like 1/2 + 1/4 + 1/16... You can't get all decimal values to be stored exactly as finite-precision binary fractions. It's just not mathematically possible.

    The only alternative is to use BigDecimal, which you can use to get exact decimal values.

提交回复
热议问题