Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 741
setzamora Avatar asked Aug 20 '09 12:08

setzamora


People also ask

What is 2f in Java?

2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

Does 2f round?

2f' means round to two decimal places. This format function returns the formatted string. It does not change the parameters.

Does string format round off?

If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.

What does %d mean in Java?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.


2 Answers

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);
like image 146
DmitryK Avatar answered Oct 14 '22 14:10

DmitryK


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.

like image 34
andersonbd1 Avatar answered Oct 14 '22 14:10

andersonbd1