Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double my money: my framework uses doubles for monetary amounts

I've inherited a project in which monetary amounts use the double type.

Worse, the framework it uses, and the framework's own classes, use double for money.

The framework ORM also handles retrieval of values from (and storage to) the database. In the database money values are type number(19, 7), but the framework ORM maps them to doubles.

Short of entirely bypassing the framework classes and ORM, is there anything I can do to calculate monetary values precisely?

Edit: yeah, I know BigDecimal should be used. The problem is that I am tightly tied to a framework that where, e.g., the class framework.commerce.pricing.ItemPriceInfo has members double mRawTotalPrice; and double mListPrice. My company's application's own code extends, e.g, this ItemPriceInfoClass.

Realistically, I can't say to my company, "scrap two years of work, and hundreds of thousands of dollars spent, basing code on this framework, because of rounding errors"

like image 610
tpdi Avatar asked Oct 05 '10 20:10

tpdi


1 Answers

If tolerable, treat the monetary type as integral. In other words, if you're working in the US, track cents instead of dollars, if cents provides the granularity you need. Doubles can accurately represent integers up to a very large value (2^53) (no rounding errors up to that value).

But really, the right thing to do is bypass the framework entirely and use something more reasonable. That's such an amateur mistake for the framework to make - who knows what else is lurking?

like image 75
Michael Petrotta Avatar answered Oct 07 '22 02:10

Michael Petrotta