1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
WJA
  • 6,676
  • 16
  • 85
  • 152
  • If you were able to get the "original" number, there wouldn't be a reason to use BigNumber in the first place. Also https://mikemcl.github.io/bignumber.js/#toN (but that of course won't help you either). Maybe you want https://mikemcl.github.io/bignumber.js/#toS ? – Felix Kling Jun 25 '15 at 14:56
  • 1
    I don't know what you are asking for. You know that JS cannot represent some numbers, but you're still trying to? – Bergi Jun 25 '15 at 14:57
  • 1
    I think you will probably have to round it to something JS can represent if you have to have the number back in "JS-land". An alternative, depending on your needs, could be to persist it as a string. – xdhmoore Jun 25 '15 at 14:59
  • 1
    What you're getting back is simply another BigNumber object. Do you want to "get back the original number" to store or display it, or do you want to perform further calculations? – m69's been on strike for years Jun 25 '15 at 15:15
  • @FelixKling that's not true. It may be that mathematically you are certain the result *is* representable in 53 bits, but intermediate operations are not. For example, consider modular arithmetic. So there are reasons to use BigNumber but cast the result to Number. – C S Nov 16 '20 at 02:44

1 Answers1

3

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

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72