当我设置时,我使用的是 BigDecimal 数据类型
new BigDecimal(21.30);
然后,我将其作为 xml 源返回,它显示为
21.30000000000710522735760100185871124467578125
另一个号码
new BigDecimal(23.11)
已返回
23.1099999994315658113818187512921995859375
我想用与创建时设置的小数位相同的小数位来显示结果。
最佳答案
The results of this constructor can be somewhat unpredictable. One might assume that writing
new BigDecimal(0.1)
in Java creates aBigDecimal
which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.This is because 0.1 cannot be represented exactly as a
double
(or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
如果您检查 BigDecimal java 文档,您会发现您必须使用带有 String
参数的构造函数才能最终实现您需要的行为。
关于Java new BigDecimal 生成另一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56257572/