Is there a way to have rails print out a number with commas in it?
For example, if I have a number 54000000.34, I can run <%= number.function %>, which would prin
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.
#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.
Yes, use the NumberHelper. The method you are looking for is number_with_delimiter.
number_with_delimiter(98765432.98, :delimiter => ",", :separator => ".")
# => 98,765,432.98
A better way for those not using rails that handles decimals:
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:
\\1
. \\1
becomes \1
when 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 \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)+(?!\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.Here is where I got the code: 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
The direct way to do this, with or without Rails, is:
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.
The following do the trick for both delimiter and precision (API ref).
ActiveSupport::NumberHelper.number_to_rounded(1234.532, delimiter: ',', precision: 1)
(or from views just number_to_rounded
, no need for the suffix)
HTH
You want the number_with_delimiter method. For example:
<%= 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, :precision => 2, :delimiter => ',') %>