For very large or very small numbers, scientific notation can be used to represent floating point values. Using scientific notation, a number can be represented as a number plus e/E, followed by a multiple of 10, such as:
The code copy is as follows:
var num1 = 3.125e7; // 31250000 var num2 = 3e-17; // 0.000000000000000000000000000000000000003
To add or subtract particularly large numbers, you can use string + scientific notation methods to perform the method, such as:
The code copy is as follows:
// Only consider large integers, and do not consider decimal function strAdd(sNum1, sNum2){
/*Add a digit to record the case where the highest digit is further*/
var sNum1 = ['0', sNum1].join(''), sNum2 = ['0', sNum2].join('');
/*Add 0 to short numeric strings*/
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('');
}
/*Convert strings to arrays and add them with corresponding digits*/
var arr1 = sNum1.split(''), arr2 = sNum2.split('');
var arrAddRes = new Array(arr1.length), i=arr1.length;
var andone = 0, // Whether the lower part addition is cur1, cur2, curAdd;
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){ // Finally, whether to go one step further, otherwise intercept the previous 0 arrAddRes.splice(0,1);
}
/*If there are the first 19 digits in the array, use scientific notation to represent the result*/
var keeplen = 19; // The decimal of js only retains the 18-digits after the decimal point var eAfter = arrAddRes.length - 1; // The multiple part after e var eBefore, eBeforeStr = ''; // The decimal part before e
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.11111111, 9]
The code is as above, isn't it very simple?