java Java中的BigDecimal问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7525284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BigDecimal Problem in java
提问by Sunil kumar
BigDecimal bd= new BigDecimal("00.0000000000");
//now bd format to 0E-10
if(BigDecimal.ZERO.equals(bd) || bd.equals("0E-10"))
{
flag=true;
}
There are two problems in the above code
上面的代码有两个问题
- why variable bdautomatically format to 0E-10
- ifcondition results false value, ie it does not enter inside ifblock.
- 为什么变量bd 会自动格式化为0E-10
- if条件结果为假值,即它不会进入if块内。
Can anyone suggest. thanks
任何人都可以建议。谢谢
回答by NPE
You've given the constructor ten digits after the decimal point, so even though all of them are zero, BigDecimal
has decided to set its internal scale
to 10. This explains the -10
in "0E-10"
.
您已经为构造函数指定了小数点后的十位数字,因此即使它们都为零,BigDecimal
也决定将其内部设置scale
为 10。这解释了-10
in "0E-10"
。
As to equals
, the Javadoc says:
至于equals
,Javadoc 说:
Compares this
BigDecimal
with the specifiedObject
for equality. UnlikecompareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
将此
BigDecimal
与指定Object
的相等进行比较。与 不同compareTo
,此方法仅在两个BigDecimal
对象的值和比例相等 时才认为它们相等(因此,通过此方法进行比较时,2.0 不等于 2.00)。
Bottom line:
底线:
- Use
compareTo()
instead ofequals()
. - Don't directly compare
BigDecimal
toString
as this won't work.
- 使用
compareTo()
代替equals()
。 - 不要直接比较
BigDecimal
,String
因为这行不通。
回答by Howard
You can test for zero using
您可以使用
bd.signum() == 0
BigDecimal.equals
also includes scale (which is 10 in your case) and thus fails. In general you should use compareTo
in order to compare BigDecimals
.
BigDecimal.equals
还包括比例(在您的情况下为 10),因此失败。一般来说,您应该使用compareTo
以进行比较BigDecimals
。
回答by Matthew Farwell
The BigDecimal uses a scale of 10 because you've given it ten digits after the decimal point, which answers your first point.
BigDecimal 使用 10 的比例,因为您在小数点后给它十位数字,这回答了您的第一点。
For the if, for the first part, you are comparing 0 with 00.00000000000 (the scale is different, so they aren't the same). In the second, you're comparing a String with a BigDecimal. Which won't work.
对于 if,对于第一部分,您将 0 与 00.00000000000 进行比较(比例不同,因此它们不相同)。在第二个中,您将 String 与 BigDecimal 进行比较。这行不通。