开发者

BigDecimal Problem in java

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

  1. why variable bd automatically format to 0E-10
  2. 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 BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal 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:

  1. Use compareTo() instead of equals().
  2. Don't directly compare BigDecimal to String as 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜