Software Development

Using BigDecimal vs Double for financial calculations involving currency data types?

KE Asked by Kevin Foster · 22-01-2024
0 upvotes 6,645 views 0 comments
The question

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

0
MA
Answered on 24-01-2024

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. 

0
B
Answered on 26-01-2024

Have you considered storing everything as "Long" representing cents or subunits to avoid decimal points entirely?

GA 27-01-2024

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.

0
SA
Answered on 28-01-2024

Definitely use BigDecimal. Verbose syntax is a small price to pay for not losing money due to floating-point math errors. 

K 29-01-2024

Totally agree. We learned the hard way when our monthly reports were off by a few dollars. BigDecimal fixed it instantly.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session