问题描述
Java的 BigDecimal
怎么会这么痛苦?
双d = 13.3D;
BigDecimal bd1 = new BigDecimal(d);
BigDecimal bd2 = new BigDecimal(String.valueOf(d));
System.out.println(结果1:+ bd1.toString());
System.out.println(结果2:+ bd2.toString());
结果1:13.300000000000000710542735760100185871124267578125
结果2:13.3
是有什么情况需要结果1吗?我知道Java 1.5改变了 toString()
方法,但这是预期的后果吗?
我也意识到 BigDecimal
有 doubleValue()
等,但我正在使用的库有助于使用 toString()
,我无法改变: - (
干杯。
嗯,确实解决了构造函数 BigDecimal(double val)中明显的不一致性
:
故事的道德:痛苦似乎是自己造成的,只需使用或而不是=)
How is it that Java's BigDecimal
can be this painful?
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
Is there any situation where Result 1 would be desired? I know that Java 1.5 changed the toString()
method but was this the intended consequence?
Also I realise that BigDecimal
has doubleValue()
etc, but the library that I am working with helpfully uses a toString()
and I can't change that :-(
Cheers.
Well, the API does address this apparent inconsistency in the constructor BigDecimal(double val)
:
Moral of the story: The pain seems self-inflicted, just use new BigDecimal(String val)
or BigDecimal.valueOf(double val)
instead =)
这篇关于“new BigDecimal(13.3D)”导致不精确的“13.3000000000000007105 ..”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!