JavaScript performs operations on large Numbers

  • 2020-03-30 04:23:36
  • OfStack

For very large or very small Numbers, floating point values can be expressed using scientific notation. Using scientific notation, a number can be expressed as a number plus e/ e, followed by multiplying by a multiple of 10, such as:


var num1 = 3.125e7; // 31250000 var num2 = 3e-17; // 0.00000000000000003

For the addition and subtraction of extremely large Numbers, the method of string + scientific notation can be used, such as:


//We only consider the case of large integers, not the decimal function strAdd(sNum1, sNum2){
 
  var sNum1 = ['0', sNum1].join(''), sNum2 = ['0', sNum2].join('');
  
  var len1 = sNum1.length, len2 = sNum2.length,
    zeroArr = function(len){
      var arr = new Array(len), i=len;
      while(i--){arr[i] = 0;}
      return arr;
    };
   if(len1 > len2){
    var arrTemp = zeroArr(len1 - len2);
    arrTemp.push(sNum2),
    sNum2 = arrTemp.join('');
  }
  else if(len2 > len1){
    var arrTemp = zeroArr(len2 - len1);
    arrTemp.push(sNum1),
    sNum1 = arrTemp.join('');
  }
   
  var arr1 = sNum1.split(''), arr2 = sNum2.split('');
   var arrAddRes = new Array(arr1.length), i=arr1.length;
   var andone = 0, //Whether the low spots add to the one & cake;       Cur1, cur2 curAdd; < br / >    while(i--){
    cur1 = +arr1[i], cur2 = +arr2[i];
    curAdd = cur1+cur2+andone;
    if(10 > curAdd)
      arrAddRes[i] = curAdd,
      andone = 0;
    else
      arrAddRes[i] = +curAdd.toString().slice(1,2),
      andone = 1;
  }
   if(!andone){ //If not, intercept the previous 0& PI;       ArrAddRes. Splice (0, 1); < br / >   }
   
  var keeplen = 19; // js Only the decimal point after the decimal point 18 position    var eAfter = arrAddRes.length - 1; // e The next multiple    var eBefore, eBeforeStr = '';      // e The decimal part in front
  if(keeplen < arrAddRes.length)
    eBeforeStr = [arrAddRes[0], '.', arrAddRes.slice(1, keeplen).join('')].join('');
  else
    eBeforeStr = [arrAddRes[0], '.', arrAddRes.slice(1).join('')].join('');
   eBefore = +eBeforeStr;
   return [Number(arrAddRes.join('')), eBefore, eAfter];
}
 strAdd('1234567890', '9876543210'); // -> [1111111100, 1.1111111, 9]

The code is as above, isn't it also very simple.


Related articles: