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()方法,但这是预期的后果吗?
另外我意识到BigDecimal有doubleValue()等,但我正在使用的库有助于使用一个toString()和我不能改变:-(
干杯。
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)
或BigDecimal.valueOf(double val)
代替=)
相关文章
- java - 设置BigDecimal的特定精度
- java - BigDecimal - 使用new或valueOf
- java - 为什么新的BigDecimal(“0.015”).compareTo(new BigDecimal(0.015))返回-1?
- java - 为什么toString不能在不可变的BigDecimal上产生正确的值?
- java - 为什么BigDecimal自然排序与equals不一致?
- Java运行时错误“非终止十进制扩展;没有精确可表示的十进制结果“在BigDecimal类中
- java - BigDecimal,精度和比例
- hibernate - JPA注释不会保留BigDecimal精度
转载注明原文:java – “new BigDecimal(13.3D)”导致不精确的“13.3000000000000007105 ..”? - 代码日志