有没有办法用js缩短一个数字?

有什么办法可以让数字变短吗?例如,1.000.000 变为 1M、1.000 变为 1k、10.000 变为 10k,依此类推



慕丝7291255
浏览 115回答 3
3回答

波斯汪

尝试这样的事情:函数 fnum(x) { if(isNaN(x)) 返回 x;if(x < 9999) {&nbsp; &nbsp; return x;}if(x < 1000000) {&nbsp; &nbsp; return Math.round(x/1000) + "K";}if( x < 10000000) {&nbsp; &nbsp; return (x/1000000).toFixed(2) + "M";}if(x < 1000000000) {&nbsp; &nbsp; return Math.round((x/1000000)) + "M";}if(x < 1000000000000) {&nbsp; &nbsp; return Math.round((x/1000000000)) + "B";}return "1T+";}

三国纷争

你可以尝试这样的事情:function shortenNum(num, decimalDigits) {&nbsp; if (isNaN(num)) {&nbsp; &nbsp; console.log(`${num} is not a number`)&nbsp; &nbsp; return false;&nbsp; }&nbsp; const magnitudes = {&nbsp; &nbsp; none: 1,&nbsp; &nbsp; k: 1000,&nbsp; &nbsp; M: 1000000,&nbsp; &nbsp; G: 1000000000,&nbsp; &nbsp; T: 1000000000000,&nbsp; &nbsp; P: 1000000000000000,&nbsp; &nbsp; E: 1000000000000000000,&nbsp; &nbsp; Z: 1000000000000000000000,&nbsp; &nbsp; Y: 1000000000000000000000000&nbsp; };&nbsp; const suffix = String(Math.abs(num)).length <= 3 ?&nbsp; &nbsp; 'none' :&nbsp; &nbsp; Object.keys(magnitudes)[Math.floor(String(Math.abs(num)).length / 3)];&nbsp; let shortenedNum&nbsp; if (decimalDigits && !isNaN(decimalDigits)) {&nbsp; &nbsp; const forRounding = Math.pow(10, decimalDigits)&nbsp; &nbsp; shortenedNum = Math.round((num / magnitudes[suffix]) * forRounding) / forRounding&nbsp; } else {&nbsp; &nbsp; shortenedNum = num / magnitudes[suffix];&nbsp; }&nbsp; 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));

慕姐8265434

如果你使用的是js库或者框架(比如Angular、React),可以使用这个数字缩写
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript