javascriptfloating-pointintfinancial

Working with accurate currency values in Javascript


I'm working on a system that uses financial data. I'm getting subtle rounding errors due to the use of floating point numbers. I'm wondering if there's a better way to deal with this.

One of the issues is that I'm working with a mixture of different currencies, which might have up to 12 decimals, and large numbers for other currencies.

This means that the smallest number I need to represent is 0.000000000001 * (1*10^-12) and the largest 100,000,000,000 (1*10^11).

Are there any recommended ways to work with numbers of this size and not lose precision?


Solution

  • If you're really trying to stay in the JS realm you might consider Decimal.js which should cover your precision range.
    If I were writing this and needed to make sure there were no rounding errors I would likely try and use a GMP extension for another lang inside a microservice which was only tasked with the financial math. GMPY2 for Python3 is probably a good bet for something quick and easy.