Efficient BigDecimal round Up and down to two decimals

后端 未结 3 467
渐次进展
渐次进展 2020-12-10 14:17

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 --->         


        
相关标签:
3条回答
  • 2020-12-10 14:40
    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
    
    0 讨论(0)
  • 2020-12-10 14:41
    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.

    0 讨论(0)
  • 2020-12-10 14:45

    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);
    }
    
    0 讨论(0)
提交回复
热议问题