Java BigDecimal:舍入到最接近的整数值

问题描述:

我需要以下结果

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

.round() .setScale()?我该怎么做?

你可以使用 setScale()将小数位数减少到零。假设保持要舍入的值:

You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded:

BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);

使用 round()多一点涉及,因为它要求您指定要保留的位数。在你的例子中,这将是3,但这对所有值都无效:

Using round() is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:

BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);

(注意 BigDecimal 对象是不可变的; setScale round 将返回一个新对象。)

(Note that BigDecimal objects are immutable; both setScale and round will return a new object.)