Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient BigDecimal round Up and down to two decimals

In java am trying to find an efficient way to round a BigDecimal to two decimals, Up or Down based on a condition.

 IF condition true then:
    12.390 ---> 12.39
    12.391 ---> 12.40
    12.395 ---> 12.40
    12.399 ---> 12.40

 If condition false then:
    12.390 ---> 12.39
    12.391 ---> 12.39
    12.395 ---> 12.39
    12.399 ---> 12.39

What is the most efficient way to accomplish this?

like image 473
richs Avatar asked Apr 15 '11 20:04

richs


2 Answers

public static BigDecimal round(BigDecimal d, int scale, boolean roundUp) {
  int mode = (roundUp) ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN;
  return d.setScale(scale, mode);
}
round(new BigDecimal("12.390"), 2, true); // => 12.39
round(new BigDecimal("12.391"), 2, true); // => 12.40
round(new BigDecimal("12.391"), 2, false); // => 12.39
round(new BigDecimal("12.399"), 2, false); // => 12.39
like image 162
maerics Avatar answered Oct 18 '22 04:10

maerics


num = num.setScale(condition ? RoundingMode.UP : RoundingMode.DOWN);

But note that your spec is not entirely clear when it comes to negative numbers. Take a look at the various rounding modes in the API doc and see what exactly you need.

like image 23
Michael Borgwardt Avatar answered Oct 18 '22 05:10

Michael Borgwardt