utils

大数相加

整数

function plus(num1, num2) {
let ret = []
const num1Arr = num1.split('')
const num2Arr = num2.split('')
let i = num1Arr.length - 1,
j = num2Arr.length - 1,
tmp = 0
while (i >= 0 && j >= 0) {
let sum = Number(num2Arr[j--]) + Number(num1Arr[i--]) + tmp
tmp = sum > 9 ? 1 : 0
sum %= 10
ret.push(sum)
}
while (i >= 0) {
let sum = Number(num1Arr[i--]) + tmp
tmp = sum > 9 ? 1 : 0
sum %= 10
ret.push(sum)
}
while (j >= 0) {
let sum = Number(num2Arr[j--]) + tmp
tmp = sum > 9 ? 1 : 0
sum %= 10
ret.push(sum)
}
if (tmp) ret.push(tmp)
return ret.reduceRight((acc, cur) => acc + cur, '')
}

金额格式化

function toThousands(num) {
let [prefix, suffix] = num.toString().split('.')
let i = 0
prefix = Array.from(prefix).reverse().join('')
let formatPrefix = ''
while (i < prefix.length) {
formatPrefix = prefix[i++] + formatPrefix
if (i % 3 === 0) {
formatPrefix = ',' + formatPrefix
}
}
return formatPrefix + '.' + suffix
}