Javascript precision with more than 15 decimals

235 Views Asked by At

I have a string which I need to convert to number.

The thing is, I have 20 decimals and JS lose precision after 15 or 17 decimals, when trying to use parseFloat.

Example:

const number = "0.0000012726726461401083"
const parseNumber = parseFloat(number) // 0.0000012726726461401084

Y try to see if libraries like big.js or decimal.js could help me, but I didn't find any solution.

1

There are 1 best solutions below

10
Adri On

What didn't suit you about decimal.js ? It looks exactly like what you would need for that, so have a go at it and try to manually set the precision : https://mikemcl.github.io/decimal.js/#precision


Since the language doesn't natively support higher precision decimals than 17, and decimal.js has a default of 20 precision which you can customize, you will have to work with such a library to perform the necessary operations. The alternative is to handle it with custom code, which unless strictly necessary would not be recommended.

When your calculations are done and you potentially need to use the resulting number elsewhere, you should use a string to do so. If you need to alternate between the string format and the decimal.js library, that is still probably the best js-only option.

If for some reason you really have to resort to native javascript numbers, it is best not to rely on shifting the decimal place as the language still only allows for a fixed precision of 53 bits : Imprecisions will still occur.