function add(a, b) {
let intNumList = []
let decNumList = []
let intCarry = 0
let decCarry = 0
const [int1 = '0', dec1 = '0'] = `${a}`.split('.')
const [int2 = '0', dec2 = '0'] = `${b}`.split('.')
const intMax = Math.max(int1.length, int2.length)
const decMax = Math.max(dec1.length, dec2.length)
const tempInt1 = int1.padStart(intMax, '0')
const tempInt2 = int2.padStart(intMax, '0')
const tempDec1 = dec1.padEnd(decMax, '0')
const tempDec2 = dec2.padEnd(decMax, '0')
for (let j = decMax - 1; j >= 0; j--) {
let temp = Number(tempDec1[j]) + Number(tempDec2[j]) + decCarry
const lessTen = temp < 10
decNumList.unshift(lessTen ? temp : temp - 10)
decCarry = lessTen ? 0 : 1
}
for (let i = intMax - 1; i >= 0; i--) {
let temp = Number(tempInt1[i]) + Number(tempInt2[i]) + intCarry + decCarry
const lessTen = temp < 10
intNumList.unshift(lessTen ? temp : temp - 10)
intCarry = lessTen ? 0 : 1
decCarry = 0
}
if (intCarry > 0) intNumList.unshift(1)
return Number([intNumList, decNumList].map((o) => o.join('')).join('.'))
}
add(0.1, 0.2)
add(617.82, 6.18)
思路总结
- 把数字转换成字符串
- 以小数点为分割点把数字分割为整数部分和小数部分
- 整数部分前面补0,位数补齐
- 小数部分后面补0,位数补齐
- 先把小数部分从后往前相加 ** 注意进位数据 **
- 再把整数部分从后往前相加 ** 注意进位数据和小数部分的位置 **
- 整数部分加完之后,如果有进位,则最前面需要补 1
- 把整数部分与小数部分的数据拼接,
- 收工