71

I have this edit form.

But when I store something such as 1.5, I would like to display it as 1.50.

How could I do that with the form helper? <%= f.text_field :cost, :class => 'cost' %>

mecyborg
  • 407
  • 3
  • 12
leonel
  • 9,968
  • 20
  • 82
  • 129

4 Answers4

169

You should use number_with_precision helper. See doc.

Example:

number_with_precision(1.5, :precision => 2)
=> 1.50 

Within you form helper:

<%= f.text_field :cost, :class => 'cost', :value => (number_with_precision(f.object.cost, :precision => 2) || 0) %>

BTW, if you really want to display some price, use number_to_currency, same page for doc (In a form context, I'd keep number_with_precision, you don't want to mess up with money symbols)


apneadiving
  • 112,549
  • 26
  • 215
  • 208
  • Brilliant and thanks! One side note is that using the `|| 0` will prevent any HTML5 placeholder value from being displayed unless the user erases the value. Also, erasing the field may cause issues with numeric validation (because there's an empty value attribute when what you want is _no_ value attribute). Nothing a little JS can't fix, but it seems like Rails should be a tad smarter in this case. – Tom Harrison Sep 18 '12 at 16:57
47

Alternatively, you can use the format string "%.2f" % 1.5. http://ruby-doc.org/docs/ProgrammingRuby/html/ref_m_kernel.html#Kernel.sprintf

gkuan
  • 921
  • 6
  • 6
11

For this I use the number_to_currency formater. Since I am in the US the defaults work fine for me.

<% price = 45.9999 %>
<price><%= number_to_currency(price)%></price>
=> <price>$45.99</price>

You can also pass in options if the defaults don't work for you. Documentation on available options at api.rubyonrails.org

codesponge
  • 210
  • 2
  • 8
7

Rails has a number_to_currency helper method which might fit you specific use case better.

Brian
  • 6,740
  • 3
  • 27
  • 27
  • I think the accepted answer is closer -- `number_to_currency` results in a formatted string that Rails cannot cast back to a float. `number_with_precision` is probably the better option. – Tom Harrison Sep 18 '12 at 17:00
  • @TomHarrisonJr sure it can be cast back to a float. `price = "$3.99"; price.slice!("$"); puts price.to_f => 3.99` It just depends on the user experience you want. Some might want the ability to put a dollar sign into the input box. I know I like having the option. – bfcoder Dec 18 '13 at 04:52