Skip to content

Instantly share code, notes, and snippets.

@loskael
Created February 18, 2022 03:10
Show Gist options
  • Save loskael/f307e5771bd845c9439a3654b24f8b0e to your computer and use it in GitHub Desktop.
Save loskael/f307e5771bd845c9439a3654b24f8b0e to your computer and use it in GitHub Desktop.
format number
/**
* 数字格式化
* @param {number} v value 被格式化的数
* @param {int} f toFixed 保留位数
* @param {int} d 被除数
* @param {Array<String>} u 单位
* @param {String} b 备胎
* @returns
*/
const fmt = (v, f = 2, d = 1e4, u = ['万', '亿'], b = '--') => {
v = parseFloat(v);
if (isNaN(v)) return b;
let s = '';
let ubak = [];
let unit = [];
while (v >= d) {
if (!ubak.length) {
ubak = [...u];
unit.push(s);
}
s = ubak.shift();
v = v / d;
}
return v.toFixed(f) + s + unit.join('');
};
// test case 1
new Array(30).fill(0).forEach((v, i) => {
v = 10 ** i;
console.log(i, fmt(v).replace(/\.0+/, ''));
});
// test case 2
new Array(30).fill(0).forEach((v, i) => {
v = 10 ** i;
console.log(i, fmt(v, 0, 1e3, ['K', 'M', 'B', 'T']));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment