1

I need to operate on Big Numbers but I need the results to be precise, like below:

const BN = require('bn.js');
var a = 11060622312717714974
var b = 1570481433500000000000;
console.log(a/b); //0.0070428227146040415

When I use Big Number I get only 0, no precision:

var aBN = new BN('11060622312717714974');
var bBN = new BN('1570481433500000000000');
console.log(aBN.div(bBN).toString()); //0

Is it possible to get precise result with this library?

TylerH
  • 20,799
  • 66
  • 75
  • 101
j809809jkdljfja
  • 767
  • 2
  • 9
  • 25

2 Answers2

4

Not familiar with the library, but having a look at the README.md file, it says:

Note: decimals are not supported in this library.

So, according to that, the answer would be no.

See https://github.com/indutny/bn.js/#usage.

Thomas Hirsch
  • 2,102
  • 3
  • 19
  • 39
  • Is there any chance this can be fixed by telling javascript (explicitly or implicitly) that we want our result to be of the built-in `Number` type rather than the no-decimals-for-you `BN` type? – Cat Mar 06 '19 at 21:18
0

Precise is a funny word in computer science and JavaScript is not exception.

Notice the input compared to the output of this:

console.log( 11060622312717714974 )

you don't always get what you want.

And there are situations like this:

console.log( .1 + .2 );
console.log(  (.1 + .2) === .3 );

So, probably not what you wanted to hear, but knowing this up front you can maybe work around it.

Anyway, checkout https://github.com/MikeMcl/bignumber.js/

TylerH
  • 20,799
  • 66
  • 75
  • 101
gkelly
  • 268
  • 1
  • 9
  • @johnerfx A common workaround for this is to multiply your floating-point number (by 10^x where x is the number of digits after the decimal point), do the division, then divide (by 10^x) again to get your "precise" result. – Cat Mar 06 '19 at 21:18