What is the maximum safe integer
MAX_SAFE_INTEGER is a constant with a value of 9007199254740991. We know that js stores all data with a double precision, and this data type can safely store values between -(253-1) and 253-1 (including boundary values).
Problems in the project
In the project we output values greater than the maximum safe integer
console.log(9007199254740999) // 9007199254741000
console.log(9007199254740997) // 9007199254740996
Copy the code
So in our project, if there is a large number of items, what should we do when we need to calculate the sum of the added numbers?
Ordinary numbers like ours can be added directly using the + sign, but for the maximum safe integer addition, how to do?
The solution
A good solution to this approach is to convert the operation to a string to avoid the arithmetic problems caused by its accuracy
For example: Define two strings:
a = '9007199254740991'
b = '9007199254740978566'
function add(a,b){
}
Copy the code
Next is the calculation of the topic, I hope I can help you in the project one day
Let a ='9007199254740991' let b =' 9007199254740978566' function add(a,b) Math.max(a.length, b.length) // a = a. padstart (maxlength, 0) b = b.paddstart (maxlength,0) let t = 0 let f= 0 let sum = '' for(var I = maxlength -1 ; i>0; i--){ t= parseInt(a[i])+parseInt(b[i])+f f= Math.floor(t/10) sum = t%10 +sum } if(f === 1){ sum = '1'+sum } return sum }Copy the code