JS千位分割方法
bmj

js千位分割

做项目时遇到的需求,因为金额较大,需要在展示时用用逗号作为千位分割,保证可读性

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
toChinesNum(num) {
num = parseInt(num);
let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let unit = ["", "十", "百", "千", "万"];
let getWan = (temp) => {
let strArr = temp.toString().split("").reverse();
let newNum = "";
for (var i = 0; i < strArr.length; i++) {
newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
}
return newNum;
}
let overWan = Math.floor(num / 10000);
let noWan = num % 10000;
if (noWan.toString().length < 4) noWan = "0" + noWan;

let chinanum = overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
return `${chinanum}`
},

参考

对vue表格数据进行格式化—阿拉伯数字转中文

 Comments