Rails number_field alternative for decimal values

Ruby on-Rails

Ruby on-Rails Problem Overview


I'm trying to accept a decimal value (USD, so 12.24 would be an example) with the number_field method.

<div class="controls">
  <%= f.number_field :amount, :class => 'text_field' %>
</div>

This only allows me to enter integer values.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can bypass the "only Integers" constraint by adding a Float for the step option:

f.number_field :amount, step: 0.5

Update: Actually you can use the value 'any' for the step, it will accept all floats and integers, and the step will be 1:

f.number_field :amount, step: :any

Update for prices:

You can use the rails' helper number_to_currency to display a price inside a number_field:

f.number_field :amount, value: number_to_currency(f.object.amount.to_f, delimiter: '', unit: ''), step: :any

Solution 2 - Ruby on-Rails

For price fields you can use this:

f.number_field :price, value: @item.price ? '%.2f' % @item.price : nil, min: 0, step: 0.01

It works fine even if you allow blank values.

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
QuestionAdrian ElderView Question on Stackoverflow
Solution 1 - Ruby on-RailsMrYoshijiView Answer on Stackoverflow
Solution 2 - Ruby on-RailscollimarcoView Answer on Stackoverflow