# 1.数字金额千分位格式化
let a = 123456789;
console.log(a.toLocaleString("en-US")); //123,456,789
1
2
2
参考链接
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
# 2.数字补 0 操作
const a1 = (num, len = 2) => `0${num}`.slice(-len);
const a2 = (num, len = 2) => `${num}`.padStart(len, "0");
a1(8);
a2(78, 5);
1
2
3
4
2
3
4
# 补充
# MDN 解释:
String.prototype.padStart()方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
参数
targetLength 当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
padString 可选 填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的默认值为 " "(U+0020)。
# 3.小数取整
let num = 123.456;
// 常用方法
console.log(parseInt(num)); // 123
// 按位或
console.log(num | 0); // 123
// “双按位非”操作符
console.log(~~num); // 123
// 左移操作符
console.log(num << 0); // 123
// 按位异或
console.log(num ^ 0); // 123
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11