是否有一个rails技巧来增加大量的逗号?

时间:2021-05-19 03:36:00

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。函数%>,输出“54,000,000.34”

thanks!

谢谢!

11 个解决方案

#1


306  

You want the number_with_delimiter method. For example:

需要使用number_with_delimiter方法。例如:

<%= number_with_delimiter(@number, :delimiter => ',') %>

Alternatively, you can use the number_with_precision method to ensure that the number is always displayed with two decimal places of precision:

或者,您可以使用number_with_precision方法来确保数字始终显示为两个精度小数点:

<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>

#2


108  

For anyone not using rails:

对于不使用rails的任何人:

number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse

#3


27  

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

#4


17  

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_delimiter method.

如果你做了很多事情,但也有FYI,因为上面没有暗示,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.

如果您使用的是最典型的方式,则不需要提供分隔符值。

#5


16  

If you want to add commas outside of views and you don't want to include some modules, you can use number_to_delimited method (rails version >= 4.02). For example:

如果想在视图之外添加逗号,又不想包含某些模块,可以使用number_to_delimited方法(rails版本>= 4.02)。例如:

#inside anywhere
ActiveSupport::NumberHelper.number_to_delimited(1000000) # => "1,000,000"

#6


10  

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.

如果您希望使用不同的分隔符,请更改regex中的最后一个'。

For bonus, this is how the regex is working:

作为奖励,以下是regex的工作方式:

  • gsub replaces everything that matches the regex with the second parameter passed to gsub. In this case that is \\1. \\1 becomes \1 when evaluated which matches the first capture group in the regex. In this regex that is (\d).
  • gsub用传递给gsub的第二个参数替换所有匹配regex的内容。在这种情况下,这是\1。当计算哪个捕获组与regex中的第一个捕获组匹配时,\1变为\1。在这个regex中(\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 \1 capture 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,456 This is because 1234 matches, 2345 matches and 3456 matches so we put a comma after the 1, the 2, and the 3.
  • (\d)(?=(\d\d\d)+)正在匹配一个数字,后面跟着一个或多个3位数的组。第一个parens集合是我们的\1捕获组,第二个parens将是\2。如果我们把它放在这里,我们会得到:123456.gsub (/(\d)(?=(\d\d)+)/,“\1”)#=> 1,2,3,456这是因为1234匹配,2345匹配和3456匹配,所以我们在1、2和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.
  • 通过添加(?!\d),我们将匹配任何在前而不在前的数字,因此(?=(\d\d\d)+(?!\d)表示匹配一个数字,后面跟着三个数字,而不是一个数字。这样做的原因是gsub会不断替换匹配字符串的东西。如果我们只替换第一场比赛那么就会得到123456789。自从123456,789仍然匹配我们的regex我们得到123456789。

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

这就是我在regex中了解到的内容:http://www.tutorialspoint.com/ruby/ruby_ruby_regular_expressions.htm

#7


7  

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.

有关更多选项,请参见活动支持核心扩展-数字-格式。

#8


2  

Another solution that does not use Helpers: format with 2 decimal places, and then replace . by ,

另一个不使用helper的解决方案是:将格式设置为小数点后两位,然后替换。由,

puts(("%.2f" % 2.5666).gsub('.',','))
>> 2,57

#9


1  

for javascript folks

对javascript的人

function numberWithDelimiter(value) {
    return (value+"").split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("")
}

:)

:)

#10


1  

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,{精度:2、单位:“})

#11


1  

  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变成一个更高的数字

#1


306  

You want the number_with_delimiter method. For example:

需要使用number_with_delimiter方法。例如:

<%= number_with_delimiter(@number, :delimiter => ',') %>

Alternatively, you can use the number_with_precision method to ensure that the number is always displayed with two decimal places of precision:

或者,您可以使用number_with_precision方法来确保数字始终显示为两个精度小数点:

<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>

#2


108  

For anyone not using rails:

对于不使用rails的任何人:

number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse

#3


27  

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

#4


17  

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_delimiter method.

如果你做了很多事情,但也有FYI,因为上面没有暗示,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.

如果您使用的是最典型的方式,则不需要提供分隔符值。

#5


16  

If you want to add commas outside of views and you don't want to include some modules, you can use number_to_delimited method (rails version >= 4.02). For example:

如果想在视图之外添加逗号,又不想包含某些模块,可以使用number_to_delimited方法(rails版本>= 4.02)。例如:

#inside anywhere
ActiveSupport::NumberHelper.number_to_delimited(1000000) # => "1,000,000"

#6


10  

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.

如果您希望使用不同的分隔符,请更改regex中的最后一个'。

For bonus, this is how the regex is working:

作为奖励,以下是regex的工作方式:

  • gsub replaces everything that matches the regex with the second parameter passed to gsub. In this case that is \\1. \\1 becomes \1 when evaluated which matches the first capture group in the regex. In this regex that is (\d).
  • gsub用传递给gsub的第二个参数替换所有匹配regex的内容。在这种情况下,这是\1。当计算哪个捕获组与regex中的第一个捕获组匹配时,\1变为\1。在这个regex中(\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 \1 capture 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,456 This is because 1234 matches, 2345 matches and 3456 matches so we put a comma after the 1, the 2, and the 3.
  • (\d)(?=(\d\d\d)+)正在匹配一个数字,后面跟着一个或多个3位数的组。第一个parens集合是我们的\1捕获组,第二个parens将是\2。如果我们把它放在这里,我们会得到:123456.gsub (/(\d)(?=(\d\d)+)/,“\1”)#=> 1,2,3,456这是因为1234匹配,2345匹配和3456匹配,所以我们在1、2和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.
  • 通过添加(?!\d),我们将匹配任何在前而不在前的数字,因此(?=(\d\d\d)+(?!\d)表示匹配一个数字,后面跟着三个数字,而不是一个数字。这样做的原因是gsub会不断替换匹配字符串的东西。如果我们只替换第一场比赛那么就会得到123456789。自从123456,789仍然匹配我们的regex我们得到123456789。

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

这就是我在regex中了解到的内容:http://www.tutorialspoint.com/ruby/ruby_ruby_regular_expressions.htm

#7


7  

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.

有关更多选项,请参见活动支持核心扩展-数字-格式。

#8


2  

Another solution that does not use Helpers: format with 2 decimal places, and then replace . by ,

另一个不使用helper的解决方案是:将格式设置为小数点后两位,然后替换。由,

puts(("%.2f" % 2.5666).gsub('.',','))
>> 2,57

#9


1  

for javascript folks

对javascript的人

function numberWithDelimiter(value) {
    return (value+"").split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("")
}

:)

:)

#10


1  

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,{精度:2、单位:“})

#11


1  

  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变成一个更高的数字