分享JS实现千位分隔符的两种方法
自己最好在 VScode 进行练习,看不如动手来得深刻
方法一:普通方法
const moneyFormat = (num) => {
const arr = num.toString().split(".");
const _arr = arr[0].split("").reverse();
const temp = [];
_arr.forEach((item, index) => {
if (index % 3 === 0 && index !== 0) {
temp.push(",");
}
temp.push(item);
});
arr[0] = temp.reverse().join("");
return arr.join(".");
};
方法二:正则的方法(个人喜欢)
<script>
function numFormat(num) {
var res = num.toString().replace(/\d+/, function (n) { // 先提取整数部分
return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
return $1 + ",";
});
})
return res;
}
var num1 = 45465454654513;
var num2 = 87985513.464984;
console.log(numFormat(num1)); // 45,465,454,654,513
console.log(numFormat(num2)); // 87,985,513.464984
</script>
路漫漫其修远兮,吾将上下而求索