Skip to content
Advertisement

Prevent round off in String.format(“%.2f”, doubleValue) in Java

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement