Home >Web Front-end >JS Tutorial >JavaScript implements large number operations_javascript skills

JavaScript implements large number operations_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:30:232138browse

For very large or very small numbers, floating point values ​​can be represented in scientific notation. Using scientific notation, you can express a number as a number plus e/E, followed by a multiple of 10, such as:

Copy code The code is as follows:

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

To perform addition and subtraction of particularly large numbers, you can use string scientific notation, such as:

Copy code The code is as follows:

// Only large integers are considered here, decimals are not considered function strAdd(sNum1, sNum2){
/*Add one digit to record the situation where the highest digit is advanced by one*/
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 the string into an array and add the corresponding digits*/
var arr1 = sNum1.split(''), arr2 = sNum2.split('');
var arrAddRes = new Array(arr1.length), i=arr1.length;
var andone = 0, // Whether to add one to the low bit 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){ // Whether to add one at the end, otherwise intercept the previous 0 arrAddRes.splice(0,1);
}
/*If the first 19 digits of the array are intercepted, use scientific notation to express the result*/
var keeplen = 19; // JS decimals only keep 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.1111111, 9]

The code is as above, is it very simple?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn