问题
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