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

Ruby on-RailsRubyRuby on-Rails-3Forms

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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)


Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleonelView Question on Stackoverflow
Solution 1 - Ruby on-RailsapneadivingView Answer on Stackoverflow
Solution 2 - Ruby on-RailsgkuanView Answer on Stackoverflow
Solution 3 - Ruby on-RailscodespongeView Answer on Stackoverflow
Solution 4 - Ruby on-RailsBrianView Answer on Stackoverflow