/**
* 数字格式化10000 => 10k
* @param num 需要格式化的数字
* @param digits 小数保留位数
*/
function numberFormatter(num, digits) {
const si = [
{value: 1E18, symbol: 'E'},
{value: 1E15, symbol: 'P'},
{value: 1E12, symbol: 'T'},
{value: 1E9, symbol: 'G'},
{value: 1E6, symbol: 'M'},
{value: 1E3, symbol: 'k'}
];
for (let i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
}
}
return num.toString();
}
//用法:
numberFormatter(12345678, 3); // 12.346M
网友评论