BigDecimal equals() trap: scale matters, not just value

BigDecimal .equals() trap — 2-hour debug story new BigDecimal("10.00").equals(new BigDecimal("10.0")) → false. If your payment system compares amounts with .equals(), you already have a bug. You just haven't seen the ticket yet. Here's how I learned this — 4 PM on a tired Tuesday last month. A unit test asserting that a calculated total matched an expected value. Values looked identical on screen. Test kept failing. Same number. Different scale. equals() compares both value AND scale. The fix: compareTo() == 0 I had read this in Effective Java, Item 62. I had caught it in code review on someone else's code three months earlier. When I wrote the test myself at 4 PM, I still forgot. Two real lessons: 1. BigDecimal is quietly vicious. Scale matters. Rounding mode matters. And new BigDecimal(0.1) is NOT the same as new BigDecimal("0.1") — the first one is 0.1000000000000000055511151231257827021181583404541015625. Your unit test won't catch it if both sides use the double constructor. 2. Knowing the rule and using the rule are different skills. Reviewing someone else's code with a fresh brain is easy. Catching your own mistake at end of day is not. This is why code review exists — we're blind to our own bugs. I keep a 60-second checklist now for anything money-adjacent: → BigDecimal with String constructor ONLY → compareTo, never equals → RoundingMode always explicit (HALF_EVEN for banking) → No float or double anywhere near currency → Scale set explicitly at the boundary What's the smallest bug that cost you the most time? #Java #BackendDevelopment

  • text

I hit this exact bug while building the MoneyUtils class for my payment orchestrator project. Fix is in the Featured section of my profile 👆 if anyone wants to see the final version with JUnit tests. The 3 places it bit me most: 1. Cart total vs discount threshold 2. Idempotency check — stored vs incoming amount 3. Reconciliation — PSP response vs ledger Money math is not number math. Which scenario have you hit?

Like
Reply

To view or add a comment, sign in

Explore content categories