是否有任何人都知道的用于格式化“缩写”的良好 JavaScript 片段?数字?
关键是缩写。例如,用 1m
代替 1000000
,用 12k
代替 12000
等 - 很像 StackOverflow!
除了我尝试过的之外,我不确定还需要添加什么:
格式数字缩写 javascript
formatnumbersshortjavascript
还有其他一些搜索和搜索结果,但没有运气。我觉得有人以前一定做过这样的事,讨厌重新发明轮子之类的!
干杯
编辑:我正在寻找一个数字,即12345
并将其转换为12k
抱歉我不太清楚!
The key is abbreviated. For example, 1m
instead of 1000000
, and 12k
instead of 12000
etc. - much like on StackOverflow!
I'm not sure what else to add other than I've tried:
format numbers abbreviated javascript
format numbers short javascript
And a few other searches and scoured the results with no luck. I feel like someone must have done this before, hate reinventing wheels and all that!
Cheers
Edit: I'm looking to take a number, i.e. 12345
and turn it into 12k
Sorry I wasn't very clear!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我很久以前编写的一些代码,但它运行良好。它甚至支持小数。
Here's some code I've written quite some time ago but it works fine. It even supports decimals.
我制作了一个 npm 包,可以为您执行此操作: https://www.npmjs.com/ package/approximate-number
用于 Node.js(或通过 Browserify 的浏览器):
然后在您的代码中:
或者,通过 Bower 在浏览器中使用:
然后
I made an npm package that can do this for you: https://www.npmjs.com/package/approximate-number
Usage for Node.js (or browsers via Browserify):
and then in your code:
Or, for usage in browsers via Bower:
And then
如果我理解正确的话,您有一个数字
n
并且想要将其格式化为字符串。然后应该做该工作。您当然可以根据您的需要进行扩展,甚至可以包含数字
< 1.
.If I understand correctly, you have a number
n
and want to format it to a string. Thenshould do the job. You can of course extend it to your needs or even include numbers
< 1
.