Skip to content

Instantly share code, notes, and snippets.

@alaq
Created June 8, 2017 22:05
Show Gist options
  • Save alaq/6e64fa5ba242b75aee55c8784c90ccbb to your computer and use it in GitHub Desktop.
Save alaq/6e64fa5ba242b75aee55c8784c90ccbb to your computer and use it in GitHub Desktop.
JavaScript function to sum two strings as numbers and return the full string (no scientific notation).
function sumStrings(a,b) {
var arrayA = a.split('').reverse();
var arrayB = b.split('').reverse();
var arrayAB = [];
var remnants = 0;
for (var i = 0 ; i < Math.max(arrayA.length,arrayB.length); i++){
// if string is longer a or b, will clean up at the end
if (!arrayA[i]) arrayA[i] = '0';
if (!arrayB[i]) arrayB[i] = '0';
arrayAB[i] = (parseInt(arrayA[i]) + parseInt(arrayB[i]) + remnants) % 10;
if (((parseInt(arrayA[i]) + parseInt(arrayB[i])) + remnants) > 9) remnants = 1;
else remnants = 0;
}
var stringNumber = arrayAB.reverse().join('');
if (remnants === 1) stringNumber = '1' + stringNumber;
while (stringNumber[0] === '0'){
stringNumber = stringNumber.slice(1);
}
return stringNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment