在JS中为1000000至1M和1000至1K等 [英] 1000000 to 1M and 1000 to 1K and so on in JS

查看:479
本文介绍了在JS中为1000000至1M和1000至1K等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
是否有办法对数字进行四舍五入变成友好的格式? (例如,1.1万美元)
如何格式化类似于Stack Overflow信誉格式的数字

Possible Duplicate:
Is there a way round numbers into a friendly format? (e.g. $1.1k)
How to format numbers similar to Stack Overflow reputation format

我在JS中有很多数字,我想让它们以更短,更容易理解的方式出现..

I have long numbers in JS and I'd like to make them appear in a shorter, and more eaisier to understand way..

所以:

1,000,000 = 1M

1,200,000 = 1.2M

1,450 = 1.45K and so on...

有什么想法可以在JS或JQuery中实现吗?

Any ideas how I could do this in JS or JQuery?

推荐答案

只是为了好玩,请查看高尔夫代码:友好号码缩写

Just for fun, check out Code Golf: Friendly Number Abbreviator

最短的JS答案:

function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}

p.s.这可能不是最快或最好的解决方案.

p.s. this is probably not the fastest or best solution.

重复:是有没有一种方法可以将数字四舍五入为易于阅读的格式? (例如$ 1.1k)

这篇关于在JS中为1000000至1M和1000至1K等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆