BigDecimal class from java.lang.Math package is useful for scale manipulation. Be careful though when you want to compare two BigDecimal objects with equals() method since it tests not just the equality of value but also the scale as mentioned in the document as below:
…..this method considers two BigDecimals equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
For the following code
BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");
if (a.equals(b)){
System.out.println("Equals");
}else{
System.out.println("Not Equals");
}
it will return "Not Equals” as the scales of the objects are different.
To compare values of the above two objects, compareTo method can be used as it implements Comparable interface like wrappers.
if (a.compareTo(b)==0)
{
System.out.println("They have same value");
}

1 comments:
Do abs method accept BigDecimal value? Or do I need to double value for the abs method to function.
Post a Comment