Files
uniapp-im-shop/utils/index.js
2025-12-26 02:15:32 +08:00

32 lines
712 B
JavaScript

/**
* 金额格式化
* @param {*} amount 金额
* @returns
*/
export const formatRMB = amount => {
// 处理 null、undefined 或非数字输入
if (amount == null || amount === '') {
return '0.00'
}
// 转为数字
let num = Number(amount)
if (isNaN(num)) {
return '0.00'
}
// 保留两位小数(四舍五入)
num = Math.round(num * 100) / 100
// 转为固定两位小数字符串
let str = num.toFixed(2)
// 分离整数和小数部分
const [integer, decimal] = str.split('.')
// 添加千分位分隔符(从右往左每三位加逗号)
const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
return `${formattedInteger}.${decimal}`
}