gpt4 book ai didi

java - BigDecimal(double) 构造函数的不可预测性

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:53 25 4
gpt4 key购买 nike

我最近开始在一个项目中使用 Sonar,并且在使用构造函数 new BigDecimal(double val) 时遇到了一条 PMD 规则被破坏的情况。当我阅读java文档时,我发现 new BigDecimal(double val) 有点不可预测,我应该使用可预测的 new BigDecimal(String val)

这是javadoc对BigDecimal的说法public BigDecimal(double val):

Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.

Notes:

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.

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

为什么这个构造函数真的存在? new BigDecimal(String val) 还不足以解决这个问题吗?我什么时候应该使用 new BigDecimal(double val) 构造函数?

最佳答案

Why does this constructor really exists?

它将 double 的实际表示值转换为 BigDecimal。 BigDecimal 的全部要点是提供尽可能多的精度,这就是此构造函数的作用。

如果您想要通过对 Double.toString(double) 进行少量舍入而获得的值,您可以使用

System.out.println(BigDecimal.valueOf(0.1));

打印

0.1

When should I use the new BigDecimal(double val) constructor

当你想知道double真正代表的值时。您可以根据需要应用自己的舍入。

当您使用double时,您应该始终应用合理的舍入。但是,如果您这样做,您可能会发现您不需要 BigDecimal。 ;)

关于java - BigDecimal(double) 构造函数的不可预测性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com