I'm building a billing module in Java and noticed some weird rounding errors when adding up totals using the Double data type. I've read that I should be using BigDecimal instead, but I'm worried about the performance hit and the more verbose syntax. Why exactly does Double fail for money, and is the overhead of BigDecimal significant for a high-frequency trading app?
3 answers
Double is a floating-point type based on the IEEE 754 standard, which represents numbers in binary. Many decimal fractions (like 0.1) cannot be represented exactly in binary, leading to tiny precision errors that accumulate. For money, this is unacceptable. BigDecimal provides absolute precision because it handles numbers as integers with a scale. While it is slower than primitive doubles because it's an object-based type, the "performance hit" is negligible for 99% of applications. Unless you are doing millions of operations per millisecond, the safety of your financial data is worth the extra few microseconds of execution time.
Have you considered storing everything as "Long" representing cents or subunits to avoid decimal points entirely?
Definitely use BigDecimal. Verbose syntax is a small price to pay for not losing money due to floating-point math errors.
Totally agree. We learned the hard way when our monthly reports were off by a few dollars. BigDecimal fixed it instantly.
Brandon, that’s a common trick, but how do you handle fractional cents or different exchange rates? If you use Long, you eventually hit a wall with divisions or multi-currency conversions. BigDecimal handles those rounding modes (like HALF_UP) natively, making the logic much easier to audit than custom integer math.