千分位显示金额

前端之家收集整理的这篇文章主要介绍了千分位显示金额前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

网站很多代码,普遍是使用正则

function thousandBitSeparator(num) {
    return num && num
        .toString()
        .replace(/(\d)(?=(\d{3})+\.)/g,function($0,$1) {
            return $1 + ",";
        });
}

然而,对于3000,4500这些却是不适用的

改进版的正则是,但是仍然有点问题(例如45200)

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

 

正则看的有点头大,一般情况下,使用自带方法就好

(12345678).toLocaleString("en-US") => "12,345,678"
//Number.toLocaleString()

 

 

测试:

let testNum = 1000

function thousandBitSeparator1(num) {
    return num && num
        .toString()
        .replace(/(\d)(?=(\d{3})+\.)/g,";
        });
}

function thousandBitSeparator2(num) {
  return num && (num
    .toString().indexOf(.) != -1 ? num.toString().replace(/(\d)(?=(\d{3})+\.)/g,";
    }));
}

function thousandBitSeparator3(num) {
  return num.toLocaleString(en-US)
}

console.log(thousandBitSeparator1(testNum))  
console.log(thousandBitSeparator2(testNum))
console.log(thousandBitSeparator3(testNum))

分享图片

 

 



let testNum = 45200

function thousandBitSeparator1(num) {
    return num && num
        .toString()
        .replace(/(\d)(?=(\d{3})+\.)/g,";
    }));
}

function thousandBitSeparator3(num) {
  return num.toLocaleString(en-US)
}

console.log(thousandBitSeparator1(testNum))
console.log(thousandBitSeparator2(testNum))
console.log(thousandBitSeparator3(testNum))

分享图片

 

 

 

https://segmentfault.com/q/1010000004651380

https://www.cnblogs.com/freeyiyi1993/p/4603525.html

猜你在找的正则表达式相关文章