Ruby-on-rails 是否有将逗号添加到大数的 rails 技巧?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1078347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a rails trick to adding commas to large numbers?
提问by Jess
Is there a way to have rails print out a number with commas in it?
有没有办法让 rails 打印出一个带有逗号的数字?
For example, if I have a number 54000000.34, I can run <%= number.function %>, which would print out "54,000,000.34"
例如,如果我有一个数字 54000000.34,我可以运行 <%= number.function %>,它会打印出“54,000,000.34”
thanks!
谢谢!
回答by John Topley
You want the number_with_delimitermethod. For example:
你想要number_with_delimiter方法。例如:
<%= number_with_delimiter(@number, :delimiter => ',') %>
Alternatively, you can use the number_with_precisionmethod to ensure that the number is always displayed with two decimal places of precision:
或者,您可以使用该number_with_precision方法来确保数字始终以两位小数精度显示:
<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>
回答by pguardiario
For anyone not using rails:
对于不使用导轨的任何人:
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse
回答by PatrikAkerstrand
Yes, use the NumberHelper. The method you are looking for is number_with_delimiter.
是的,使用NumberHelper。您正在寻找的方法是number_with_delimiter。
number_with_delimiter(98765432.98, :delimiter => ",", :separator => ".")
# => 98,765,432.98
回答by chocolateboy
The direct way to do this, with or without Rails, is:
使用或不使用 Rails的直接方法是:
require 'active_support/core_ext/numeric/conversions'
12345.to_s(:delimited) # => "12,345"
12345.6789.to_s(:delimited) # => "12,345.6789"
For more options, see Active Support Core Extensions - Numeric - Formatting.
有关更多选项,请参阅Active Support Core Extensions - Numeric - Formatting。
回答by Alexander Ryhlitsky
If you want to add commas outside of views and you don't want to include some modules, you can use number_to_delimitedmethod (rails version >= 4.02). For example:
如果您想在视图之外添加逗号并且不想包含某些模块,则可以使用number_to_delimited方法(rails 版本 >= 4.02)。例如:
#inside anywhere
ActiveSupport::NumberHelper.number_to_delimited(1000000) # => "1,000,000"
回答by coloradoblue
If you're doing it a lot but also FYI because it's not implied by the above, Rails has sensible defaults for the number_with_delimitermethod.
如果你经常这样做但也仅供参考,因为上面没有暗示它,Rails 为该number_with_delimiter方法提供了合理的默认值。
#inside controller or view
number_with_delimiter(2444323.4)
#=> 2,444,323.30
#inside console
helper.number_with_delimiter(233423)
#=> 233,423
No need to supply the delimiter value if you're doing it the most typical way.
如果您以最典型的方式进行操作,则无需提供分隔符值。
回答by fxfilmxf
A better way for those not using rails that handles decimals:
对于那些不使用处理小数的 rails 的人来说,更好的方法是:
parts = number.to_s.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\1,")
parts.join('.')
If you want a different delimiter, change the last ',' in the regex.
如果您想要不同的分隔符,请更改正则表达式中的最后一个“,”。
For bonus, this is how the regex is working:
对于奖金,这是正则表达式的工作方式:
- gsub replaces everything that matches the regex with the second parameter passed to gsub. In this case that is
\\1.\\1becomes\1when evaluated which matches the first capture group in the regex. In this regex that is(\d). (\d)(?=(\d\d\d)+)is matching a digit followed by 1 or more groups of 3 digits. The first set of parens is our\1capture group, the second would be\2. If we were just to leave it at that we would get:123456.gsub!(/(\d)(?=(\d\d\d)+)/, "\\1,") #=> 1,2,3,456This is because 1234 matches, 2345 matches and 3456 matches so we put a comma after the 1, the 2, and the 3.- By adding the (?!\d) we are matching anything that comes before that doesn't precede a digit so
(\d)(?=(\d\d\d)+(?!\d))means match a digit followed by 3 digits that is not followed by a digit. The reason why this works is that gsub will keep replacing things that match the string. If we were only going to replace the first match then for a number like 123456789 we would get 123456,789. Since 123456,789 still matches our regex we get 123,456,789.
- gsub 用传递给 gsub 的第二个参数替换与正则表达式匹配的所有内容。在这种情况下,即
\\1. 评估时\\1变为\1与正则表达式中的第一个捕获组匹配。在这个正则表达式中,(\d). (\d)(?=(\d\d\d)+)匹配一个数字,后跟一组或多组 3 位数字。第一组括号是我们的\1捕获组,第二组是\2. 如果我们只是保留它,我们会得到:123456.gsub!(/(\d)(?=(\d\d\d)+)/, "\\1,") #=> 1,2,3,456这是因为 1234 个匹配项、2345 个匹配项和 3456 个匹配项,所以我们在 1、2 和 3 后面放了一个逗号。- 通过添加 (?!\d) 我们正在匹配前面没有数字的任何东西,因此
(\d)(?=(\d\d\d)+(?!\d))意味着匹配一个数字,后跟 3 个数字,后跟不跟一个数字。这样做的原因是 gsub 将不断替换与字符串匹配的内容。如果我们只想替换第一个匹配项,那么对于像 123456789 这样的数字,我们将得到 123456,789。由于 123456,789 仍然匹配我们的正则表达式,我们得到 123,456,789。
Here is where I got the code: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/number_helper.rb#L298-L300
这是我得到代码的地方:https: //github.com/rails/rails/blob/master/activesupport/lib/active_support/number_helper.rb#L298-L300
And here is where I learned about what is going on in that regex: http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm
这是我了解正则表达式中发生的事情的地方:http: //www.tutorialspoint.com/ruby/ruby_regular_expressions.htm
回答by Nino van Hooff
Another solution that does not use Helpers: format with 2 decimal places, and then replace . by ,
另一个不使用 Helpers 的解决方案:格式化为 2 个小数位,然后替换 . 经过 ,
puts(("%.2f" % 2.5666).gsub('.',','))
>> 2,57
回答by Le Duc Duy
You can use methods from ActiveSupport
您可以使用以下方法 ActiveSupport
For example:
例如:
ActiveSupport::NumberHelper::number_to_currency(10000.1234,{precision: 2,unit: ''})
ActiveSupport::NumberHelper::number_to_currency(10000.1234,{precision: 2,unit: ''})
回答by Justin Cox
def add_commas(numstring)
correct_idxs = (1..100).to_a.select{|n| n % 6 == 0}.map{|n| n - 1}
numstring.reverse.chars.join(",").chars.select.with_index{|x, i| i.even? || correct_idxs.include?(i)}.join.reverse
end
This was my way in ruby
这是我在 ruby 中的方式
Addition edit: Basically it adds all commas in between the numbers and only selects the ones where the index + 1 % 6
添加编辑:基本上它会在数字之间添加所有逗号,并且只选择索引 + 1 % 6 的那些
I figured the commas up to 100 was fine but if you want a super long number just make 100 a higher number
我认为最多 100 的逗号很好,但如果你想要一个超长的数字,只需将 100 设为更高的数字

