Java keep trailing 0 in float operations

醉酒当歌 提交于 2019-12-20 06:38:15

问题


the code:

Float f = Float.parseFloat("1.80");
System.out.println(f);

prints "1.8" on screen. I need to keep the 0 in the float value (Float f) for some validation. How do I do this?


回答1:


You are confusing a number value and its formatting. It is not possible to actually store 1.80 as a float, however it is possible to display the number as a formatted String which forces two decimal places. Your options are:

  1. Keep the original String that the user entered, if the number of decimal places they gave
    matters

  2. Store the number as a float, but when displaying the number force it to display with two decimal places like this:

    System.out.printf("%.2f\n", f);




回答2:


That's simply a formatting issue:

System.out.printf("%.2f\n", f);



回答3:


  1. Floating point variables don't have decimal places. They have binary places.
  2. 1.8 and 1.80 are the same number, and they are represented the same way in a float or double.
  3. If you want them presented with a certain number of decimal places, you have to convert to a decimal radix, via either BigDecimal or DecimalFormat, where you can control the number of decimal places.

In short the question doesn't really make sense as posed.



来源:https://stackoverflow.com/questions/15374904/java-keep-trailing-0-in-float-operations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!