Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 802
leonel Avatar asked Oct 14 '11 19:10

leonel


People also ask

How do you print double up to 2 decimal places?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places.


4 Answers

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)


like image 174
apneadiving Avatar answered Oct 04 '22 18:10

apneadiving


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

like image 25
gkuan Avatar answered Oct 04 '22 19:10

gkuan


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

like image 28
codesponge Avatar answered Oct 04 '22 17:10

codesponge


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

like image 40
Brian Avatar answered Oct 04 '22 19:10

Brian