liujie
12 小时以前 fddf3d913d47f391f84f9e460cb76d427ef02c44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * 通用格式化工具(用户端)
 * 约定:后端金额统一以「分」下发,前端展示统一转为「元」
 */
 
/**
 * 金额分 → 元
 * @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
}