What's the right way to parseFloat in Java

后端 未结 7 1757
[愿得一人]
[愿得一人] 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:26

    The problem is simply that float has finite precision; it cannot represent 0.0065 exactly. (The same is true of double, of course: it has greater precision, but still finite.)

    A further problem, which makes the above problem more obvious, is that 0.001 is a double rather than a float, so your float is getting promoted to a double to perform the subtraction, and of course at that point the system has no way to recover the missing precision that a double could have represented to begin with. To address that, you would write:

    float f = Float.parseFloat("0.0065") - 0.001f;
    

    using 0.001f instead of 0.001.

提交回复
热议问题