Set number of decimal places to 0 if float is an i

2019-08-07 09:31发布

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?

3条回答
Explosion°爆炸
2楼-- · 2019-08-07 10:09

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.

查看更多
放我归山
3楼-- · 2019-08-07 10:21
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.

查看更多
爷的心禁止访问
4楼-- · 2019-08-07 10:24

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.

查看更多
登录 后发表回答