Java new BigDecimal 生成另一个数字
Java new BigDecimal generates another number
我使用 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
a BigDecimal
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
参数的构造函数来结束您需要的行为。
我使用 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
参数的构造函数来结束您需要的行为。