Search code examples
javascriptbignumbignumber.js

Trying to handle big numbers with bignumber.js


My issue is that I have to do calculations with big numbers (large decimals) in javascript, such as:

1.1e-40 + 1.1e-40 

Javascript only supports up to 16 digits of accuracy. So I revert to the library of MikeMcl bignumber.js

As explained in the API, to perform a calculation you do:

var y1 = new BigNumber(1.1e-40)   
var y2 = new BigNumber(1.1e-40)  

var yy = y1.plus(y2);

However, yy returns an object with

c: [220], e: -40 and s: 1

How can I use this to get back the original number?

For example I tried: yy.c * Math.pow(10, yy.e) but this gives a rounding error: 2.1999999999999998e-38.


Solution

  • As @Felix Kling says in the comment, if you want to use the native js numbers back, you'll also get their limitations.

    You can, however, print the bignumbers as strings, like yy.toString().

    Do you want to transform them from strings to native js numbers, ignoring the downsides? use parseFloat(): parseFloat(ee.toString())