Ruby-on-rails 十进制值的 Rails number_field 替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18898947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails number_field alternative for decimal values
提问by Adrian Elder
I'm trying to accept a decimal value (USD, so 12.24 would be an example) with the number_field method.
我试图用 number_field 方法接受一个十进制值(美元,所以 12.24 就是一个例子)。
<div class="controls">
<%= f.number_field :amount, :class => 'text_field' %>
</div>
This only allows me to enter integer values.
这仅允许我输入整数值。
回答by MrYoshiji
You can bypass the "only Integers" constraint by adding a Float for the step option:
您可以通过为 step 选项添加 Float 来绕过“仅整数”约束:
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:
更新:实际上您可以使用值 'any' 作为 step,它将接受所有浮点数和整数,并且 step 将为 1:
f.number_field :amount, step: :any
Update for prices:
价格更新:
You can use the rails' helper number_to_currencyto display a price inside a number_field:
您可以使用 rails 的助手number_to_currency在 number_field 中显示价格:
f.number_field :amount, value: number_to_currency(f.object.amount.to_f, delimiter: '', unit: ''), step: :any
回答by collimarco
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.
即使您允许空白值,它也能正常工作。

