BigDecimal bd= new BigDecimal("00.0000000000");
//now bd format to 0E-10
if(BigDecimal.ZE开发者_如何转开发RO.equals(bd) || bd.equals("0E-10"))
{
flag=true;
}
There are two problems in the above code
- why variable bd automatically format to 0E-10
- if condition results false value, ie it does not enter inside if block.
Can anyone suggest. thanks
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
BigDecimalwith the specifiedObjectfor equality. UnlikecompareTo, this method considers twoBigDecimalobjects 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:
- Use
compareTo()instead ofequals(). - Don't directly compare
BigDecimaltoStringas this won't work.
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.
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.
加载中,请稍侯......
精彩评论