Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 765
Sunil kumar Avatar asked Sep 23 '11 06:09

Sunil kumar


People also ask

How do I stop rounding in BigDecimal?

math. BigDecimal. round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.

What is BigDecimal in Java?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

What can I use instead of BigDecimal?

If you need to use division in your arithmetic, you need to use double instead of BigDecimal.

How do I get rid of trailing zeros in BigDecimal?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.


2 Answers

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.
like image 134
NPE Avatar answered Oct 16 '22 20:10

NPE


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.

like image 31
Howard Avatar answered Oct 16 '22 22:10

Howard