js格式化金额字段算法 避免js精度问题,保留两位小数,保持精度(小数点后两位四舍五入)
/**
* 格式化金额字段算法 保持精度 需后端返回的均为字符串金额数据
* @param {String} num 传入金额
* @returns
*/
export function thousandMark(num) {
let d = '' + num
d = d.split('.')
if (d.length == 1) {
d.push('00')
}else if (d.length == 2) {
if (d[1].length > 2) {
if (d[1][2] >= 5) {
d[1] = String(Number(d[1].slice(0, 2)) + 1)
console.log(d[0], d[1], '[0]')
if (d[1].length > 2) {
d[0] = String(Number(d[0]) + Number(d[1][0]))
console.log(d[0],d[1],'[1]')
d[1] = d[1].slice(1, 3)
}
}
d[1] = d[1].slice(0, 2)
} else if (d[1].length == 1) {
d[1] = d[1] + '0'
} else if (!d[1] || d[1].length == 0) {
d[1] = '00'
}
} else {
d[0] = '0'
d[1] = '00'
}
d[0] = d[0].replace(/\B(?=(?:\d{3})+$)/g, ',')
d = d[0] + '.' + d[1]
return d
}
实例
console.log(thousandMark('1324323112432421.094555'))
console.log(thousandMark('1324323112432421.095'))
console.log(thousandMark('1324323112432421.095'))
console.log(thousandMark('1324323112432421.995'))