概述
在JavaScript中,进行大数相加时,由于JavaScript的Number类型有一定的精度限制,直接相加可能会导致精度损失
解决方案
- 将大数转换为字符串,使用字符串拼接的方式实现大数相加,对相加后的字符串从低位到高位逐位求和并处理进位, 返回结果
function bigNumAdd(num1, num2) {let s1 = num1.toString()let s2 = num2.toString()const len = Math.max(s1.length, s2.length) // 取两者长度最大值s1 = s1.padStart(len, '0') // 长度不够补 0s2 = s2.padStart(len, '0')let carry = 0 // 进位值let result = '' // 结果for(let i = len - 1; i >= 0; i--) {const sum = +s1[i] + +s2[i] + carry // 当前位相加再加上进位值result = sum % 10 + result // 取余数作为当前位carry = Math.floor(sum / 10) // 向下取整作为进位值}// 如果最高位的进位值大于0if(carry) {result = carry + result}return result
}
bigNumAdd('123456798', '12345678900') // '12469135698'
- 使用BigInt类型:JavaScript提供了BigInt类型,可以用于表示任意大小的整数。使用BigInt进行大数相加可以避免普通Number类型的精度限制问题
let sum = BigInt('123456798') + BigInt('12345678900')
console.log(sum) // 12469135698nconsole.log(BigInt(0.1) + BigInt(0.2))
// BigInt 只可以表示整数,不能表示小数
// Uncaught RangeError: The number 0.1 cannot be converted to a BigInt because it is not an integer