最新通知
js 对数字加逗号处理
阅读次数:238 最后编辑时间:1970年01月01日

概述

在我们展示金额的时候,在大金额下阅读比较困得,采用每千分位添加一位逗号,来展示数据,更容易阅读

1、正则表达式:正则替换

const toThousands = (num = 0) => {
    return num.toString().replace(/\d+/, function(n) {
        return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    });
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111

2、字符串排序:倒序排列

const toThousands = (num = 0) => {
    let result = '';
    let numArr = num.toString().split('.');
    let int = numArr[0];
    let decmial = numArr[1] ? '.' + numArr[1] : '';
    for (let n = int.length - 1; n >= 0; n--) {
        result += int[int.length - n - 1];
        if ((int.length - n - 1) % 3 === 0 && n !== 0) {
            result += ',';
        }
    }
    return result + decmial;
};

console.log(toThousands(1234567890.111)); //1,234,567,890.111

3、字符串模板:使用slice 不断截取,不断分割

function toThousands(num = 0) {
    let result = '';
    let numArr = num.toString().split('.');
    let int = numArr[0];
    let decmial = numArr[1] ? '.' + numArr[1] : '';
    while (int.length > 3) {
        result = ',' + int.slice(-3) + result;
        int = int.slice(0, int.length - 3);
    }
    if (int) {
        result = int + result;
    }
    return result + decmial;
}

console.log(toThousands(1234567890.111));