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
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.
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.
If you need to use division in your arithmetic, you need to use double instead of 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.
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.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With