[SalesForce] The Do’s and Don’ts of currency calculations in Apex

Ok, I am not a math expert, but I know about the basics of rounding problematics in programming languages.

In one of my apps, I do some quite complex (math-wise and infrastructure -wise) currency calculations, e.g.:

  • Using SUM() on Decimal fields in AggregateResult SOQL query on million of records
  • Applying Exchange Rates to those values in Apex using regular * Math
  • Doing basic math (+-*/) with high value Decimals (billions of dollars)

In my small-number test everything is working fine, but when I let my code run on billion of USD amounts I see some big rounding errors. As the calculations are somewhat complex I first post this question before I dig into analysis.

Are there Do's and Don't when it comes to currency math in Apex?

Sorry for not providing more details here, but I was unable to extract the important parts without exposing tom much.

Especially reading this blog post from Appirio left me with bad feelings 😉

Best Answer

Don't use Double because of the loss of precision due to the floating point representation. Do use Decimal. If you're familiar with Java the Decimal class in Apex is the equivalent of the BigDecimal.

Write lots of good unit tests.

Related Topic