Sum of large numbers

The js Number is a 64-bits double of IEEE 754 standard, which means that all integers up to 2^53 are accurate. However, if the Number exceeds this range, the accuracy will be lost. The maximum safe value is 2^53-1

The way to solve the problem is to add bits in the form of a string, that is, we usually calculate the addition, and add bits, more than ten into a line of thought

let sumBig = function(a,b){ a = a.split('') ; b = b.split('') let alength = a.length; let blength = b.length; if(alength>blength){ for(let i=0; i<(alength-blength); i++){ b.unshift('0') } }else if(blength>alength){ for(let i=0; i<blength-alength+1; I++) {a.u nshift (' 0 ')}} / / ⬆ make the digits are the same, the lack of filled with 0 let newArr = []; // preliminary result array // preliminary add for(let I =0; i<a.length; i++){ newArr[i] = Number(a[i])+Number(b[i]); } var n = 0; // carry // Font-Family: heliostat; // Font-Family: heliostat; i<newArr.length; i++){ if(i===newArr.length-1){ newArr[newArr.length-i-1] = (newArr[newArr.length-i-1]+n) }else{ if(newArr[newArr.length-i-1]+n>9){ newArr[newArr.length-i-1] = (newArr[newArr.length-i-1]+n)%10; n=1 }else{ newArr[newArr.length-i-1] = newArr[newArr.length-i-1]+n; n=0; } } } return newArr.join('') } let rusult1 = sumBig('9999999999999999999999999','9999') console.log(rusult1)Copy the code

2 Handwritten template string method

// Template string

const temple = "I'm {{name}}. I'm {{age}} years old."; const data = { name: "aa", age: "10" }; String.prototype.render = function (data) { return this.replace(/{{(.*?) }}/g, (match, key) => data[key.trim()]); }; const result = temple.render(data);Copy the code