views:

924

answers:

2

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!

+8  A: 

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
PatrikAkerstrand
+11  A: 

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 => ',') %>
John Topley
Can this be used in a helper i.e module? or is it just for views? is there a equivalent method for a moudle? thanks
Mo
@Mo It's a view helper method. You should be able to use it from a module by including `ActionView::Helpers::NumberHelper` within the module.
John Topley