MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.65k stars 742 forks source link

BigNumber.parseJSON #224

Closed poldridge closed 5 years ago

poldridge commented 5 years ago

This adds a BigNumber.parseJSON method that supports arbitrary precision within JSON, by replacing all numbers in the result with BigNumbers. JSON has arbitrary precision, but JSON.parse converts all JSON numbers to JavaScript numbers which causes a loss of precision.

JSON.parse( '1e-999' ) === 0;
// vs.
BigNumber.parseJSON( '1e-999' ).eq( new BigNumber( '1e-999' ) )

This provides a method for parsing JSON without risk of losing number precision. It requires JSON.parse to be available, which is ES5; but is also available as a global object in ES3 via https://github.com/douglascrockford/JSON-js/blob/master/json2.js ; so anyone using this library that requires ES3 compatibility would also need to include json2.js as a dependency.