views:

1808

answers:

4

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.

+2  A: 
doubleValue = 123.459
doubleValue = Math.ceil(doubleValue*100)/100;
Alex
+2  A: 

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);
DmitryK
+1  A: 

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.

andersonbd1
A: 

Or format it to %.3f and truncate.

CPerkins