How to round off a float value so that it should not contain 0 after decimal

≯℡__Kan透↙ 提交于 2019-12-25 06:14:18

问题


How to round off a float value if the value is like:

eg:

  • 1.0 ==> then it should return 1
  • 2.0 ==> then it should return 2

but if the value is like:

  • 1.2 ==> then it should return 1.2

  • 1.90 ==>then it should return 1.9

I have tried to round off it and also tries different solutions but that doesn't worked for me.


回答1:


You can create a helper function like this

 static public void Normalize(String pattern, double value ) {
    DecimalFormat formatter = new DecimalFormat(pattern);
    String normalizedValue = formatter.format(value);
    System.out.println(normalizedValue);
    }

Normalize("0.#####",2.40); // 2.4
Normalize("0.#####",2.0); // 2

This worked for me.




回答2:


What you're talking about here is a display issue. The "0" in the 1.0 shows how accurate the number is, if you are only displaying 1 then the person reading does not know how accurate that value is (compared with 1.1, 1.9 or even 1.0003).

My suggestion would be to convert your answer to a string and check if the last value is "0", and if so remove it for display purposes (or some other formatting solution).

Note: I wouldn't recommend doing this because it changes the meaning of the value.



来源:https://stackoverflow.com/questions/30396740/how-to-round-off-a-float-value-so-that-it-should-not-contain-0-after-decimal

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