Rails number_field 替代十进制值

我尝试使用 number _ field 方法接受一个十进制值(USD,因此12.24将是一个示例)。

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

这只允许我输入整数值。

66506 次浏览

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

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.