What's the right way to parseFloat in Java

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

    From the Java Tutorials page on Primitive Data Types:

    A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.

    So I think your literals (0.001) are doubles and you're subtracting doubles from floats.

    Try this instead:

    System.out.println((0.0065F - 0.001D)); // 0.005500000134110451
    System.out.println((0.0065F - 0.001F)); // 0.0055
    

    ... and you'll get:

    0.005500000134110451
    0.0055
    

    So add F suffixes to your literals and you should get better results:

    Float.parseFloat("0.0065") - 0.001F
    new Float("0.027") - 0.001F
    Float.valueOf("0.074") - 0.001F
    

提交回复
热议问题