Skip to main content

Posts

Showing posts from September, 2015

Add big numbers in Javascript as strings.

function pad(a, b) { for (var i = 0; i < b.length - a.length; i++) { a = "0" + a; } return a; } function stringAdd(a, b) { var total = ""; var carry = 0; a = pad(a, b); b = pad(b, a); for (var i = b.length - 1; i >= 0; i = i - 1) { var x = (parseInt(a[i]) + parseInt(b[i]) + carry); carry = 0; if (x >= 10) { carry = 1; x = x - 10; } total = x.toString() + total; } if (carry == 1) { total = "1" + total; } return total; }