三国纷争
你可以尝试这样的事情: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 || '');}// testsconsole.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));