Efficient BigDecimal round Up and down to two decimals

落花浮王杯 提交于 2019-11-27 05:59:32

问题


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?


回答1:


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



回答2:


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.




回答3:


I suggest the following (standing on the shoulders of giants...):

public BigDecimal roundNumber(final BigDecimal number, final boolean isFloor){
     return number.setScale(2, isFloor ? RoundingMode.FLOOR 
                                       : RoundingMode.CEILING);
}


来源:https://stackoverflow.com/questions/5681868/efficient-bigdecimal-round-up-and-down-to-two-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!