Proper Use of java.math.BigDecimal: String Constructor and compareTo for Accurate Calculations
This article explains why the java.math.BigDecimal(double) constructor can cause precision loss, recommends using the String constructor for monetary values, and advises comparing BigDecimal instances with compareTo instead of equals to avoid scale‑related mismatches.
BigDecimal Constructor Usage: java.math.BigDecimal#BigDecimal(java.lang.String)
When converting a floating‑point number to a BigDecimal using the java.math.BigDecimal#BigDecimal(double) constructor, precision loss can occur.
It is essential to use the constructor that accepts a String to avoid precision loss, especially in monetary calculations.
java.math.BigDecimal#BigDecimal(String)
Use the compareTo method to compare BigDecimal, not the equals method
As with the previous post, the equals method only returns true when both objects are of the same type and have the same scale.
public boolean equals(Object x) { if (!(x instanceof BigDecimal xDec)) return false; if (x == this) return true; if (scale != xDec.scale) return false; long s = this.intCompact; long xs = xDec.intCompact; if (s != INFLATED) { if (xs == INFLATED) xs = compactValFor(xDec.intVal); return xs == s; } else if (xs != INFLATED) return xs == compactValFor(this.intVal); return this.inflated().equals(xDec.inflated()); }
If the types differ, equals returns false:
if (!(x instanceof BigDecimal xDec)) return false;
And if the scales differ, it also returns false:
if (scale != xDec.scale) return false;
The java.math.BigDecimal#compareTo method ignores scale, so it should be used for comparisons:
Method java.math.BigDecimal#compareTo will ignore precision differences and must be used for comparing BigDecimal values.
Summary
Considering precision issues, java.math.BigDecimal must be instantiated with the String constructor and compared using the compareTo method.
Alibaba's "Java Development Manual" also enforces this rule:
【Mandatory】 As shown above, BigDecimal equality comparison should use compareTo() instead of equals(). Explanation: equals() compares both value and scale (e.g., 1.0 vs 1.00 returns false), while compareTo() ignores scale.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.