mattnewbie mattnewbie - 5 months ago 95
Javascript Question

Given the string representations of two integers, return the string representation of the sum of those integers

For example:

sumStrings('1','2') // => '3'
C# sumStrings("1","2") // => "3"


My code:

function sumStrings(a,b) {
a = Number(a);
b = Number(b);
var total = a + b ;
return total.toString();
}


When I try the above code with the following, it has a problem.

sumStrings('712569312664357328695151392', '8100824045303269669937');


I get :

7.125774134884027e+26


Instead of:

712577413488402631964821329


Help please!

Answer

Your result is being returned to you in floating point because it is greater than the maximum integer value.

The max int value in javascript I believe is 9007199254740991.

You can check the limits by viewing: alert([ Number.MAX_VALUE, Number.MIN_VALUE ]);

Edit: If you need big integer math without loss of precision, you need a biginteger library similar to this: https://github.com/peterolson/BigInteger.js