给数字添加逗号 [英] Adding commas to a number

查看:62
本文介绍了给数字添加逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 1234567 之类的数字变为 1,234,567,但需要一些帮助.我的想法是我可以使用 \d{3} 拆分,然后加入 , .但问题是 \d{3} 从另一端将它分组,所以它就像我不想要的 123,456,7.

I'm trying to make a number like 1234567 go to be 1,234,567, but need some help. My thoughts were that I could use a split with \d{3} and then join a , to that. The problem with this though is that \d{3} groups it from the other end so it would be like 123,456,7 which I don't want.

非常感谢您的帮助!

推荐答案

我会使用 Rails 的 ActiveSupport(即使我没有将 Rails 用于实际应用程序),它也可以针对当前语言环境正确格式化.如果您还没有使用 Rails,则需要安装 gem:

I'd use Rails' ActiveSupport (even if I wasn't using Rails for the actual application), which also formats it properly for the current locale. If you aren't already using Rails, you'll need to install the gem:

gem install activesupport

然后,像这样要求它:

require "active_support/core_ext"

然后你可以这样做:

=> ActiveSupport::NumberHelper.number_to_delimited(1234567)
=> "1,234,567"

这篇关于给数字添加逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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