Close

Java - How to set BigDecimal Precision?

[Last Updated: May 22, 2018]

Java Number Classes Java 

Following example shows how to round BigDecimal to desired decimal places. The example also applies all available RoundingModes to understand the difference between each of them.

public class BigDecimalPrecisionExample {
  public static void main(String[] args) {
      BigDecimal bd = new BigDecimal(1.422222);
      System.out.println(bd);
      applyRounding(bd);

      BigDecimal bd2 = new BigDecimal(1.42666);
      System.out.println(bd2);
      applyRounding(bd2);
  }

  private static void applyRounding(BigDecimal bd){
      for (RoundingMode roundingMode : RoundingMode.values()) {
          if (roundingMode == RoundingMode.UNNECESSARY) {
              continue;
          }
          BigDecimal result = bd.setScale(2, roundingMode);
          System.out.printf("RoundingMode: %s, result: %s%n", roundingMode, result);
      }
  }
}
1.422222000000000097230667961412109434604644775390625
RoundingMode: UP, result: 1.43
RoundingMode: DOWN, result: 1.42
RoundingMode: CEILING, result: 1.43
RoundingMode: FLOOR, result: 1.42
RoundingMode: HALF_UP, result: 1.42
RoundingMode: HALF_DOWN, result: 1.42
RoundingMode: HALF_EVEN, result: 1.42
1.4266600000000000392219590139575302600860595703125
RoundingMode: UP, result: 1.43
RoundingMode: DOWN, result: 1.42
RoundingMode: CEILING, result: 1.43
RoundingMode: FLOOR, result: 1.42
RoundingMode: HALF_UP, result: 1.43
RoundingMode: HALF_DOWN, result: 1.43
RoundingMode: HALF_EVEN, result: 1.43

See Also