### 使用java.math.MathContext

#### 5 个答案:

E.g。将小数点后的三位数字更改为两位数的数字，然后向上舍入：

``````BigDecimal original = new BigDecimal("1.235");
BigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP);
``````

@jatan

`BigDecimal.round()` vs。任何其他`BigDecimal`方法都没有什么特别之处。在所有情况下，`MathContext`指定有效位数和舍入技术。基本上，每`MathContext`有两部分。有精确度，还有`RoundingMode`

`RoundingMode`部分指定了我们应该如何处理精度损失。要重复使用该示例，如果您使用`123`作为数字，并要求2位有效数字，那么您的精确度就会降低。使用`RoundingMode` `HALF_UP`（默认模式），`123`将变为`120`。使用`RoundingMode` `CEILING`，您将获得`130`

``````System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
``````

``````123.4
1.2E+2
1.3E+2
2E+2
``````

``````MathContext MATH_CTX = new MathContext(3, RoundingMode.HALF_UP);
``````

``````BigDecimal d1 = new BigDecimal(1234.4, MATH_CTX);
System.out.println(d1);
``````

``````BigDecimal d2 = new BigDecimal(0.000000454770054, MATH_CTX);
System.out.println(d2);
``````

``````BigDecimal d3 = new BigDecimal(0.001000045477, MATH_CTX);
System.out.println(d3);  // 0.00100

BigDecimal d4 = new BigDecimal(0.200000477, MATH_CTX);
System.out.println(d4);   // 0.200

BigDecimal d5 = new BigDecimal(0.000000004, MATH_CTX);
System.out.println(d5); //4.00E-9
``````

``````System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(20)));

System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(10)));

System.out.println(new BigDecimal("1234567890.123456789",
new MathContext(5)));
``````

``````1234567890.123456789
1234567890
1.2346E+9
``````

`BigDecimal Number = 0.5294`舍入 0.53

`Number = 1.5294`四舍五入为`1.5`

`Number = 10.5294`四舍五入为`10`

`Number = 101.5294`四舍五入为`100`

....等等