Rails 3. How do I display two decimal places in an edit form?

I have this form of editing.

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

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

+61
ruby ruby-on-rails ruby-on-rails-3 forms
Oct 14 '11 at 19:53
source share
4 answers

You should use the number_with_precision . See the document .

Example:

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

A helper is created inside you:

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

By the way, if you really want to display some price, use number_to_currency , the same page for doc (in the context of the form, I would save number_with_precision , you do not want to ruin the money symbols)




+148
Oct. 14 '11 at 19:59
source share

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

+42
Oct 14 2018-11-11T00:
source share

For this, I use formater number_to_currency . Since I am in the USA, the work is fine for me by default.

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

You can also pass options if the defaults do not work for you. Documentation on available options at api.rubyonrails.org

+9
Oct 14 2018-11-11T00:
source share

Rails has a number_to_currency helper method that works best for your specific use case.

+7
Oct. 14 2018-11-11T00:
source share



All Articles