Superlarge number addition problem?

Js, like any language, has limits on the range of values. If we want to add a large integer (> number.max_safe_INTEGER), but want to print the general form, we cannot do this with +. Once the Number exceeds number.max_safe_INTEGER, the Number is immediately converted to scientific notation. And there will be errors in numerical accuracy compared with the past. At this point you need to implement a set of addition algorithms.

function add(str1, str2) {
   if (Number(str1) > Number(str2)) {
     var len = str1;
   } else {
     var len = str2;
   }
   var len1 = str1.length;
   var len2 = str2.length;
   var temp = 0;
   var total = [];

   for (let i = 0; i < len.length; i++) {
     temp += Number(str1.charAt(len1 - i - 1)) + Number(str2.charAt(len2 - i - 1));
     if (temp > 9) {
       // If the sum of the two numbers is greater than 9, the remainder is put into total
       // temp=1 and add the next pair
       total.unshift(temp % 10);
       temp = 1;
     } else {
       // If the sum of the two numbers is less than 10, put the remainder directly into total
       total.unshift(temp);
       temp = 0;
     }
   }
   total = total.join("");
   return total
 }
 const num1 = '111111111111111111111111111111111111111'
 const num2 = '222222222222222222222222222222222222222'
 document.write(add(num1, num2));   / / the result for 333333333333333333333333333333333333333
Copy the code