问题
How do I prevent String.format("%.2f", doubleValue); from rounding off (round half up algorithm) instead of just truncating it?
e.g.
doubleValue = 123.459
after formatting,
doubleValue = 123.46
I just want to discard the last digit,
123.45
I know there are other ways to do this, I just want to know if this is possible using the String.format.
回答1:
You can always set the rounding mode:
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
and then use String.Format() HALF_EVEN is used by default, but you can change it to CEILING
another no so flexible approach will be (but this is not what you asked about):
DecimalFormat df = new DecimalFormat("###.##");
df.format(123.459);
回答2:
Looks like the answer is a big fat NO. http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#dndec "then the value will be rounded using the round half up algorithm"
I find it odd they'd do that, since NumberFormatter allows you to set RoundingMode. But as you say, there's other ways to do it. The obviously easiest being subtract .005 from your value first.
回答3:
doubleValue = 123.459
doubleValue = Math.ceil(doubleValue*100)/100;
回答4:
use String.format("%.2f", doubleValue - .005)
来源:https://stackoverflow.com/questions/1305827/prevent-round-off-in-string-format-2f-doublevalue-in-java