1. Home > programming >

Javascript realizes the operation of large numbers_javascript skills

For very large or very small numbers, you can use scientific notation to represent floating-point values. Using scientific notation, a number can be expressed as a number plus e/E, followed by a multiple of 10, such as:

< /U> The code is as follows:


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

For the addition and subtraction of very large numbers, you can use string + scientific notation to perform, such as:

The code is as follows:


// Only big In the case of integers, decimals are not considered. function strAdd(sNum1, sNum2){
/*Add one digit to record the highest digit advance*/
var sNum1 = ['0', sNum1]. join(''), sNum2 = ['0', sNum2].join('');
/*Add 0 to the short number string*/
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 the low-order addition is advanced 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 advance at the end, otherwise intercept the previous 0 arrAddRes.splice(0,1);
}
/*Before the array interception If there are 19 digits, use scientific notation to represent the result*/
var keeplen = 19; // js decimals only retain 18 digits after the decimal point var eAfter = arrAddRes.length-1; // after e Var eBefore, eBeforeStr =''; // fractional part before e
if(keeplen 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? Content recommendation: free high-definition PNG material download

This article is published by www.internetweblist.com and does not represent the position of www.internetweblist.com/:http://www.internetweblist.com/programming/52498.html

Contact Us

Online consultation:click here to give a message