javascript 格式化钱的单位,支持自定义基准单位、自定义单位列表
static formatMoneyUnit(num, unitList = [], baseUnit = '万') {
if (isNaN(num)) return { num }
let origin = num;
if (Number(num) <= 1) num = Math.abs(num)
const unit = ['亿', '千万', '百万', '十万', '万', '千', '百', '元']
const divide = [100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 1]
unitList = unitList || unit
let divideList = unitList.map(item => {
let index = unit.findIndex(i => i === item)
return divide[index]
})
if (!divideList?.length) return { num: origin, unit: baseUnit, origin: origin }
baseUnit = baseUnit || unitList[unitList.length - 1]
let unitIndex = unitList.findIndex(u => u === baseUnit)
if (unitIndex < 0) return { num }
num = num * divideList[unitIndex]
const hit = divideList.findIndex(der => Math.floor(num / der) >= 1)
if (hit < 0) return { num }
let prev = origin < 0 ? '-' : '';
return {
origin: origin,
num: prev + (num / divideList[hit]).toFixed(2),
unit: unitList[hit]
}
}```