给数字添加逗号
我正在尝试将 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"