import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRoundingDemo {
public static void main(String[] args) {
BigDecimal value = new BigDecimal("123.456789");
System.out.println("Original value: " + value);
// Round to 2 decimal places with different rounding modes
BigDecimal roundHalfUp = value.setScale(2, RoundingMode.HALF_UP);
System.out.println("HALF_UP: " + roundHalfUp); // 123.46
BigDecimal roundHalfDown = value.setScale(2, RoundingMode.HALF_DOWN);
System.out.println("HALF_DOWN: " + roundHalfDown); // 123.46
BigDecimal roundHalfEven = value.setScale(2, RoundingMode.HALF_EVEN);
System.out.println("HALF_EVEN: " + roundHalfEven); // 123.46
BigDecimal roundUp = value.setScale(2, RoundingMode.UP);
System.out.println("UP: " + roundUp); // 123.46
BigDecimal roundDown = value.setScale(2, RoundingMode.DOWN);
System.out.println("DOWN: " + roundDown); // 123.45
BigDecimal roundCeiling = value.setScale(2, RoundingMode.CEILING);
System.out.println("CEILING: " + roundCeiling); // 123.46
BigDecimal roundFloor = value.setScale(2, RoundingMode.FLOOR);
System.out.println("FLOOR: " + roundFloor); // 123.45
// Attempt rounding with UNNECESSARY (throws exception if rounding required)
try {
BigDecimal noRounding = value.setScale(6, RoundingMode.UNNECESSARY);
System.out.println("UNNECESSARY (no rounding needed): " + noRounding);
} catch (ArithmeticException e) {
System.out.println("UNNECESSARY rounding required exception: " + e.getMessage());
}
}
}