萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 千分位格式化與還原:正則替換與 split/join 實現

金額顯示常需千分位分隔符(1,234.56),提交時需還原為純數字。兩個純函數搞定。

添加千分位

function commafy(num){
    // 保留兩位小數並轉字符串
    const str = Number(num).toFixed(2) + '';
    // 正則:捕獲整數部分每三位
    return str.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 或作者原版 while 循環替換
function commafyOld(num){
    let str = Number(num).toFixed(2) + '';
    const re = /(-?\d+)(\d{3})/;
    while(re.test(str)){
        str = str.replace(re, '$1,$2');
    }
    return str;
}

去除千分位

function decommafy(str){
    return parseFloat(str.replace(/,/g, ''));
}

測試

console.log(commafy(1234567.891)); // "1,234,567.89"
console.log(decommafy("1,234,567.89")); // 1234567.89

現代化補充

Intl.NumberFormat 原生國際化格式化,支援語言環境、貨幣符號、精度控制:

const fmt = new Intl.NumberFormat('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
fmt.format(1234567.891); // "1,234,567.89"

// 解析回數字(需去除分隔符)
Number('1,234,567.89'.replace(/,/g, ''));

生產環境優先用 Intl,兼容性極佳(IE11+),且自動適應用戶地區習慣。

copyright © 萬盛學電腦網 all rights reserved