Rails: Is there a rails trick to adding commas to large numbers?

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 print out "54,000,000.34"

thanks!


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 => ',') %>

For anyone not using rails:

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

The direct way to do this, with or without Rails, is:

require 'active_support'
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.