gpt4 book ai didi

java - "new BigDecimal(13.3D)"结果不精确 "13.3000000000000007105.."?

转载 作者:太空狗 更新时间:2023-10-29 22:41:49 24 4
gpt4 key购买 nike

Java 的 BigDecimal 怎么会这么痛苦?

Double d = 13.3D;

BigDecimal bd1 = new BigDecimal(d);
BigDecimal bd2 = new BigDecimal(String.valueOf(d));


System.out.println("RESULT 1: "+bd1.toString());
System.out.println("RESULT 2: "+bd2.toString());

RESULT 1: 13.300000000000000710542735760100185871124267578125
RESULT 2: 13.3

是否存在需要结果 1 的情况?我知道 Java 1.5 更改了 toString() 方法,但这是预期的结果吗?

我还意识到 BigDecimaldoubleValue() 等,但是我正在使用的库有用地使用了 toString() 和我无法改变这一点:-(

干杯。

最佳答案

嗯,API确实解决了构造函数中这种明显的不一致 BigDecimal(double val):

  1. 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.

  2. 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.

  3. 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)BigDecimal.valueOf(double val)相反 =)

关于java - "new BigDecimal(13.3D)"结果不精确 "13.3000000000000007105.."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/460755/

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