There are two big numbers:

var a = 63829983432984289347293874; 

and

 var b = 90938498237058927340892374089; 

I need to output their sum as a string: "91002328220491911630239667963" , but when summing up I get a floating-point number 9.100232822049192e + 28.
How to convert this floating point number to the string to be output?

Reported as a duplicate at Grundy. javascript Mar 5 at 9:04 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    no, you need to initially store the lines and use some library for long arithmetic. You can also implement addition yourself - Grundy
  • Thanks, the implementation of the addition helped! - Valeriy Petukhov

2 answers 2

Something like this:

 var a = 63829983432984289347293874; var b = 90938498237058927340892374089; var stringSum = (a + b).toPrecision(40).split('.')[0] console.log('stringSum = ', stringSum); 

  • An interesting solution, only I need to get an exact result, as in the problem - Valeriy Petukhov
  • For those conditions that you submitted, the solution is correct. If you need the fractional part, remove the .split('.')[0] and cut off the extra zeros or bring it to the accuracy you need. The direction I gave you. Further or dare, or specify the conditions of the problem. - Spomni
  • one
    Well, you understand that the result of the addition of 4 + 9 by no means can end with 2, as in your example? - andreymal
  • I sprinkle my head with ashes ... On some platforms, NaN gives out as a result of addition. There will be time, I will figure out what's what and edit the answer, with a note that it is not correct and why. - Spomni

It turned out the exact value only when I used my own function to add large numbers:

 var a = '63829983432984289347293874'; var b = '90938498237058927340892374089'; function res(a, b, result, carry, base) { if (a.length == 0 && b.length == 0 && !carry) return result; var left = parseInt(a.pop() || '0', 10); var right = parseInt(b.pop() || '0', 10); var l = left + right + (carry || 0); return res(a, b, l % base + (result || ""), Math.floor(l / base), base); } function add(a, b) { return res(a.toString().split(""), b.toString().split(""), "", "", 10).toString(); } console.log(add(a, b)); 

  • Something this code does not work and gives solid NaN - andreymal
  • @andreymal, there variables in the lines should be immediately, but not large numbers - Grundy