Sunil kumar
Sunil kumar

Reputation: 337

BigDecimal Problem in java

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

  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

Upvotes: 8

Views: 26126

Answers (3)

NPE
NPE

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 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.

Upvotes: 17

Matthew Farwell
Matthew Farwell

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

Howard
Howard

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

Related Questions