0

How to get precise integer result for multiplication and division operations of huge numbers in JS?

Let's say we have:

var a = 75643564363473453456342378564387956906736546456235342;
var b = 34986098309687982743378379458582778387652482;

Multiplying these numbers gives me a number in scientific "e" notation. How to display the whole precise integer result number?

I've tried using this library https://github.com/peterolson/BigInteger.js

Readme says:

Note that Javascript numbers larger than 9007199254740992 and smaller than -9007199254740992 are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings.

But how do you do math with strings?

Un1
  • 3,874
  • 12
  • 37
  • 79

2 Answers2

3

Use bigInt, as you hinted, you need to use strings instead of numbers to represent them correctly.

bigInt("75643564363473453456342378564387956906736546456235342").multiply("34986098309687982743378379458582778387652482");
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • Thanks. But it returns an array, could you also advise how to make it a string? `.join("")` throws an error `result.join is not a function` if I try to join the variable `var result` containing that operation – Un1 Jul 27 '17 at 13:40
  • That becomes another question entirely... "How to make BigInteger work with floating numbers?" And I am sorry, but I cannot answer this. – Salketer Jul 27 '17 at 14:11
  • Well, yeah, I can see the same thing in Python. Not sure why. Thanks for the answer anyway – Un1 Jul 27 '17 at 14:16
  • Python is better with Mathematics than javascript... At least that's why researchers say they use that instead... But I couldn't say. – Salketer Jul 27 '17 at 14:22
-1

I think this question is duplicate of how-to-avoid-scientific-notation-for-large-numbers-in-javascript

This function taken from above link.

function toFixed(x) {
 if (Math.abs(x) < 1.0) {
 var e = parseInt(x.toString().split('e-')[1]);
 if (e) {
    x *= Math.pow(10,e-1);
    x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
  }
} else {
var e = parseInt(x.toString().split('+')[1]);
if (e > 20) {
    e -= 20;
    x /= Math.pow(10,e);
    x += (new Array(e+1)).join('0');
 }
}
 return x;
}

 alert(toFixed(a*b));
Sarath Kumar
  • 1,136
  • 1
  • 18
  • 41