将数字转化为“千分” xxx,xxx 形式的字符串的几种方法
1. 字符串操作
1 function format(num) { 2 let [int, fraction = ''] = (num + '').split('.'); 3 let ans = ''; 4 const len = int.length; 5 int = int.split('').reverse(); 6 for (let i = 0; i < len; i++) { 7 if (i !== 0 && i % 3 === 0) { 8 ans = int[i] + ',' + ans; 9 } else { 10 ans = int[i] + ans; 11 } 12 } 13 14 if (fraction !== '') ans += '.' + fraction; 15 16 return ans; 17 }
2. 数学运算
1 function format(num) { 2 let n = num; 3 let tmp = 0; 4 let ans = ''; 5 do { 6 // 123456.7 % 1000 => 456.6999999.. 7 mod = n % 1000; 8 // 123456 / 1000 => 123.4567 9 n /= 1000; 10 // ~~456.6999999.. => 456 11 tmp = ~~mod; 12 ans = (n >= 1 ? `${tmp}`.padStart(3, '0') : tmp) + (ans === '' ? '' : ',' + ans); 13 } while (n >= 1); 14 15 const start = num + ''; 16 const idx = start.indexOf('.'); 17 if (idx > -1) ans += start.substring(idx); 18 19 return ans; 20 }
3. 正则匹配
1 function format(num) { 2 const reg = /\d{1,3}(?=(\d{3})+$)/g; 3 const [int, frac] = String(num).split('.'); 4 return int.replaceAll(reg, '$&,') + '.' + frac; 5 }
4. Number.toLocaleString();
返回这个数字在特定语言环境下的表示字符串
let a = -1234567.8; a.toLocaleString('en-us');