Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Rounding up double value

Yong Ming Wai
Greenhorn
Posts: 12
Hie,
I need to to round double value to a 2 decimal point value.However,
the value is to be round up instead round down as per default.
E.g : 2.142 -> 2.15 (default is 2.14)
or 2.1425 -> 2.15 (default is 2.14)
Code shown below return a round down value.
***********************************************
try {
DecimalFormat df = new DecimalFormat("RM#,###,###,###.00");
if (!val.equals(null) || !val.equals("")) {
val=df.format(val);
}
} catch (Exception e) {
System.out.println(String.valueOf(e));
}
return val;
**********************************************
Anyone have any idea?
Thanks~!!

Peter Chase
Ranch Hand
Posts: 1970
Just add 0.99999... before rounding. The exact number of 9s could be a little tricky to determine; it should be perhaps a couple fewer than the typical number of significant decimal digits in a double.

If you have negative values to deal with, think about whether this will do what you want, for those.

Campbell Ritchie
Sheriff
Posts: 48424
56
Another way to do it:-
Multiply by 100, add 0.5, use the Math.round() method, and multiply by 0.01.

CR

saikrishna cinux
Ranch Hand
Posts: 689
i have one idea but i dont know whether you will accept or not
just conver the number into String and then modify the number using substring method..

Ranch Hand
Posts: 135
Do you actually want to round the binary value, or just the string representation? Strings are easier, since there are so many nice formatters. Might even be safer, depending on your app, since it doesn't modify the original value.

Paul Clapham
Sheriff
Posts: 20764
30
The BigDecimal class has a setScale() method that can be given one of several rounding modes, including "ROUND_UP".

Kentaro Shinbashi
Greenhorn
Posts: 15
Yong Ming Wai:

I think the above suggestions are good. But I think it is also important to know what your application is.

You want to round to the second decimal place, which suggests that you might be dealing with monetary values, like dollars:

\$40.00 / 3 = \$13.3333333...
Rounded up is \$13.34

So, if this is what you are dealing with, then the realm of questions changes a bit. Often, when dealing with financial calculations, it is better in the longrun to use all integer representations, for example, using an int to represent cents, and simply divide by 100 to get dollars.

Or else, use BigDecimal class.

The reason for this is that over time, errors accumulate, and sometimes, if adding a very small number to a very large number, information gets lost.

So, forgive me for going one step beyond your specific question, but I thought it might be relevent. Is it what you are trying to do?

Kentaro