WJA
WJA

Reputation: 7004

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.

Upvotes: 1

Views: 7186

Answers (2)

王浩然
王浩然

Reputation: 1

In JavaScript, the package calc-number is more useful than bignumber

import calcNumber from 'calc-number'

const result = calcNumber('0.1+0.2')
console.log(result);// result 0.3

Upvotes: 0

Tudor Constantin
Tudor Constantin

Reputation: 26861

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())

Upvotes: 3

Related Questions