RoundingMode
是 Java 中用于定义舍入行为的枚举类。它主要用于精确的数字运算,尤其是涉及到小数点的情况下。以下是 RoundingMode
的详细讲解及举例说明:
RoundingMode
常见枚举值1.1
会舍入为 2
,-1.1
会舍入为 -2
。1.9
会舍入为 1
,-1.9
会舍入为 -1
。1.1
会舍入为 2
,-1.1
会舍入为 -1
。1.9
会舍入为 1
,-1.9
会舍入为 -2
。1.5
会舍入为 2
,-1.5
会舍入为 -2
。1.5
会舍入为 1
,-1.5
会舍入为 -1
。1.5
会舍入为 2
,2.5
会舍入为 2
。ArithmeticException
)。下面通过示例来演示如何在 BigDecimal
中使用不同的 RoundingMode
:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class RoundingModeExample {
public static void main(String[] args) {
BigDecimal value1 = new BigDecimal("2.5");
BigDecimal value2 = new BigDecimal("1.1");
BigDecimal value3 = new BigDecimal("-1.1");
System.out.println("Original value: " + value1); // Original value: 2.5
System.out.println("UP: " + value1.setScale(0, RoundingMode.UP)); // UP: 3
System.out.println("DOWN: " + value1.setScale(0, RoundingMode.DOWN)); // DOWN: 2
System.out.println("CEILING: " + value1.setScale(0, RoundingMode.CEILING)); // CEILING: 3
System.out.println("FLOOR: " + value1.setScale(0, RoundingMode.FLOOR)); // FLOOR: 2
System.out.println("HALF_UP: " + value1.setScale(0, RoundingMode.HALF_UP)); // HALF_UP: 3
System.out.println("HALF_DOWN: " + value1.setScale(0, RoundingMode.HALF_DOWN)); // HALF_DOWN: 2
System.out.println("HALF_EVEN: " + value1.setScale(0, RoundingMode.HALF_EVEN)); // HALF_EVEN: 2
System.out.println("Original value: " + value2); // Original value: 1.1
System.out.println("UP: " + value2.setScale(0, RoundingMode.UP)); // UP: 2
System.out.println("DOWN: " + value2.setScale(0, RoundingMode.DOWN)); // DOWN: 1
System.out.println("CEILING: " + value2.setScale(0, RoundingMode.CEILING)); // CEILING: 2
System.out.println("FLOOR: " + value2.setScale(0, RoundingMode.FLOOR)); // FLOOR: 1
System.out.println("HALF_UP: " + value2.setScale(0, RoundingMode.HALF_UP)); // HALF_UP: 1
System.out.println("HALF_DOWN: " + value2.setScale(0, RoundingMode.HALF_DOWN)); // HALF_DOWN: 1
System.out.println("HALF_EVEN: " + value2.setScale(0, RoundingMode.HALF_EVEN)); // HALF_EVEN: 1
System.out.println("Original value: " + value3); // Original value: -1.1
System.out.println("UP: " + value3.setScale(0, RoundingMode.UP)); // UP: -2
System.out.println("DOWN: " + value3.setScale(0, RoundingMode.DOWN)); // DOWN: -1
System.out.println("CEILING: " + value3.setScale(0, RoundingMode.CEILING)); // CEILING: -1
System.out.println("FLOOR: " + value3.setScale(0, RoundingMode.FLOOR)); // FLOOR: -2
System.out.println("HALF_UP: " + value3.setScale(0, RoundingMode.HALF_UP)); // HALF_UP: -1
System.out.println("HALF_DOWN: " + value3.setScale(0, RoundingMode.HALF_DOWN)); // HALF_DOWN: -1
System.out.println("HALF_EVEN: " + value3.setScale(0, RoundingMode.HALF_EVEN)); // HALF_EVEN: -1
}
}
选择适当的 RoundingMode
可以确保在金融计算、统计分析等领域的结果精确且符合业务需求。