用js实现千位分隔符,怎么实现

如题所述

function ce(num) {
return num && (num.toString().indexOf('.') != -1 ? num.toString().replace(/(\d)(?=(\d{3})+\.)/g,
function($0, $1) {
return $1 + ",";
}) : num.toString().replace(/(\d)(?=(\d{3}))/g, function($0, $1) {
      return $1 + ",";
    }));
}
console.log(ce(1353400.23));

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-07-27
// 正则
function thousandBitSeparator(num) {
    return num && num
        .toString()
        .replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
            return $1 + ",";
        });
}
console.log(thousandBitSeparator(-1234567.9012));
// -1,234,567.9012