如何在小数点前舍入 BigDecimal?

How to round a BigDecimal before the decimal?

我有一个BigDecimal这样的
var a = new BigDecimal("1234.56") 我想将它四舍五入到小数点前两位,这样我就得到了等同于
的东西 var b = new BigDecimal("1200.00") 这样
(new BigDecimal("1200.00")).equals(b).

我目前最好的方法是
var b = new BigDecimal(a.setScale(-2, RoundingMode.HALF_UP).toPlainString()).setScale(2);
但我不确定这是否是正确的方法,因为与正尺度相比,它似乎相当冗长。这是最好的方法吗?

如果您正在使用 setScale,则无需使用 new BigDecimal,因为如果需要,它已经返回了一个新实例:

Returns a BigDecimal whose scale is the specified value

...

Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

所以,你可以更轻松地编写它:

BigDecimal b = a.setScale(-2, RoundingMode.HALF_UP).setScale(2);