When there are two integers a and b, in the usual case we have the "+" operator to add them:
let sum = a + b;
But JS has a safe range when storing integers , once the number exceeds this range, it will lose precision.
We can't run numbers with loss of precision, because the result of the operation also loses precision.
Therefore, we have to use strings to represent data! (no loss of precision)
The maximum safe range of integers in JS can be found: 9007199254740991
If we want to carry out 9007199254740991 + 1234567899999999999
We need to prepare two string variables and a method first:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b){
//...
}
Then align the string lengths:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b){
//取两个数字的最大长度
let maxLength = Math.max(a.length, b.length);
//用0去补齐长度
a = a.padStart(maxLength , 0);//"0009007199254740991"
b = b.padStart(maxLength , 0);//"1234567899999999999"
}
Then add from the ones place:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b){
//取两个数字的最大长度
let maxLength = Math.max(a.length, b.length);
//用0去补齐长度
a = a.padStart(maxLength , 0);//"0009007199254740991"
b = b.padStart(maxLength , 0);//"1234567899999999999"
//定义加法过程中需要用到的变量
let t = 0;
let f = 0; //"进位"
let sum = "";
for(let 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;
}
run:
add(a ,b); //结果为:1243575099254740990