leonel
leonel

Reputation: 10214

Rails 3. How to display two decimal places in edit form?

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' %>

Upvotes: 72

Views: 70542

Answers (5)

stevec
stevec

Reputation: 52268

This seems to work nicely, I added it to application_helper.rb

def display_2dp(form, field)
  val = form.object.send(field)
  unless val.nil?
    return '%.2f' % val 
  end
end

and use it like this:

<%= form.number_field :cost, step: 0.01, value: display_2dp(form, :cost) %>

just replace :cost with the field you're displaying.

Some advantages:

  • It can be reused on any forms in your app
  • It won't accidentally replace a nil with 0 (like what might happen with || 0)
  • It will always display exactly 2 decimal places (for example, 10.0 would appear as "10.00")

Upvotes: 0

gkuan
gkuan

Reputation: 921

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

Upvotes: 47

apneadiving
apneadiving

Reputation: 115511

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)


Upvotes: 169

codesponge
codesponge

Reputation: 220

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

Upvotes: 11

Brian
Brian

Reputation: 6840

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

Upvotes: 7

Related Questions