3 回答
TA贡献1811条经验 获得超4个赞
尝试这样的事情:
函数 fnum(x) { if(isNaN(x)) 返回 x;
if(x < 9999) {
return x;
}
if(x < 1000000) {
return Math.round(x/1000) + "K";
}
if( x < 10000000) {
return (x/1000000).toFixed(2) + "M";
}
if(x < 1000000000) {
return Math.round((x/1000000)) + "M";
}
if(x < 1000000000000) {
return Math.round((x/1000000000)) + "B";
}
return "1T+";
}
TA贡献1804条经验 获得超7个赞
你可以尝试这样的事情:
function shortenNum(num, decimalDigits) {
if (isNaN(num)) {
console.log(`${num} is not a number`)
return false;
}
const magnitudes = {
none: 1,
k: 1000,
M: 1000000,
G: 1000000000,
T: 1000000000000,
P: 1000000000000000,
E: 1000000000000000000,
Z: 1000000000000000000000,
Y: 1000000000000000000000000
};
const suffix = String(Math.abs(num)).length <= 3 ?
'none' :
Object.keys(magnitudes)[Math.floor(String(Math.abs(num)).length / 3)];
let shortenedNum
if (decimalDigits && !isNaN(decimalDigits)) {
const forRounding = Math.pow(10, decimalDigits)
shortenedNum = Math.round((num / magnitudes[suffix]) * forRounding) / forRounding
} else {
shortenedNum = num / magnitudes[suffix];
}
return String(shortenedNum) + (suffix !== 'none' && suffix || '');
}
// tests
console.log('1:', shortenNum(1));
console.log('12:', shortenNum(12));
console.log('198:', shortenNum(198));
console.log('1278:', shortenNum(1278));
console.log('1348753:', shortenNum(1348753));
console.log('7594119820:', shortenNum(7594119820));
console.log('7594119820 (rounded to 3 decimals):', shortenNum(7594119820, 3));
console.log('7594119820 (invalid rounding):', shortenNum(7594119820, 'foo'));
console.log('153000000:', shortenNum(153000000));
console.log('foo:', shortenNum('foo'));
console.log('-15467:', shortenNum(-15467));
console.log('0:', shortenNum(0));
console.log('-0:', shortenNum(-0));
添加回答
举报