1. There are three situations for comparing the size of two numbers in JS:
1. Comparing two pure numbers (Number): normal mathematical operation.
2. Compare the size of pure numbers (Number) and string numbers (String): automatically convert string numbers into pure numbers, and then perform comparisons between pure numbers
3. Compare the size of the string number (String) with the string number (String): it will be compared according to the ASCII code of the first different character
console.log( 21 > 3 ); // true
console.log( '21' > 3 ); // true
console.log( '21' > '3' ); // false
console.log( Number('21') > Number('3') ); // true
Therefore, when comparing numbers, pay attention to converting strings into numbers before comparing.
2. Compare the size of super long numbers
// 在JS中会存在数字大小操作2的53次方时会精度丢失,末尾几位变成0的情况。
// JS数字安全长度16位及以下,
console.log( '16位', 1234567891234567 ); // 1234567891234567
console.log( '17位', 12345678912345678 ); // 12345678912345678
console.log( '18位', 123456789123456789 ); // 123456789123456780
console.log( '19位', 1234567891234567891 ); // 1234567891234568000
// 精度丢失就会存在数字比较大小不准确的问题,比如:
let a = '1234567891234567891';
let b = '1234567891234567899';
console.log( Number(a) < Number(b) ) // false
// 超过16位的正整数比较大小的方法:先转成字符串再截取比较大小
if (a.length > b.length) {
console.log('a > b');
} else if (a.length < b.length) {
console.log('a < b');
} else {
const a1 = a.substr(0, 16);
const a2 = a.substr(16, a.length-16);
const b1 = b.substr(0, 16);
const b2 = b.substr(16, b.length-16);
if (Number(a1) > Number(b1) || (Number(a1) === Number(b1) && Number(a2) > Number(b2))) {
console.log('a > b');
} else if (Number(a1) < Number(b1) || (Number(a1) === Number(b1) && Number(a2) < Number(b2))) {
console.log('a < b');
} else {
console.log('a = b');
}
}
// 最后输出结果:a < b