/**
|
* 通用格式化工具(用户端)
|
* 约定:后端金额统一以「分」下发,前端展示统一转为「元」
|
*/
|
|
/**
|
* 金额分 → 元
|
* @param {Number|String} fen 金额(单位:分)
|
* @param {Boolean} [withThousands=false] 是否添加千分位分隔(如 128,000.00)
|
* @returns {String} 保留两位小数的金额字符串,如 12800000 → '128000.00'
|
*/
|
export function formatYuan(fen, withThousands = false) {
|
const num = Number(fen)
|
// 非法、空值统一按 0 处理,避免页面出现 NaN
|
const yuan = Number.isFinite(num) ? num / 100 : 0
|
const fixed = yuan.toFixed(2)
|
if (!withThousands) return fixed
|
const [intPart, decPart] = fixed.split('.')
|
return intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decPart
|
}
|