我有一个像这样的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);
关于java - 如何在小数点之前舍入 BigDecimal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68903978/