Reputation: 337
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
Can anyone suggest. thanks
Upvotes: 8
Views: 26126
Reputation: 500357
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"
.
As to equals
, the Javadoc says:
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).
Bottom line:
compareTo()
instead of equals()
.BigDecimal
to String
as this won't work.Upvotes: 17
Reputation: 61705
The BigDecimal uses a scale of 10 because you've given it ten digits after the decimal point, which answers your first point.
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.
Upvotes: 1
Reputation: 39197
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
.
Upvotes: 7