Set number of decimal places to 0 if float is an integer (java)?

怎甘沉沦 提交于 2019-12-11 11:17:59

问题


I'm using a float to hold a score. The score can be an integer or decimal. By default, floats display as 0.0, 1.0, etc. If the number does not have a decimal, I need it to display as 0, 1, etc. If it does have a decimal, then I need to display the decimal. How might I do this?


回答1:


String string;
float n = 3.0f;
if (n % 1 == 0) {
    string = String.valueOf((int) n);
} else {
    string = String.valueOf(n);
}
System.out.println("Score: " + string);

Warning: Untested code. ;)

Ok, I've tested it and fixed an error.




回答2:


You could use:

NumberFormat.getInstance().format(score);

to display with decimal places when present.

To counter against rounding errors, score here could be represented using a BigDecimal.




回答3:


Your best bet is to work out the smallest granularity of score and then use that with an appropriate multiplier.

For example, if the smallest increment is 0.01, use a multiplier of 100. And if your score % mulitplier = 0 then you know its a whole number.

That way you dont need to worry about rounding, or representation errors.



来源:https://stackoverflow.com/questions/12045137/set-number-of-decimal-places-to-0-if-float-is-an-integer-java

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