如何在simple_form数字字段(Rails)中指定十进制精度

时间:2022-05-06 16:59:11

So I have a decimal field with precision 2 in the database, meant to be used for currency. It works fine unless the last decimal place ends in 0, ie. 799.90. It will instead strip it to 799.9 when it's displayed in the field. I know about number_with_precision, but I haven't been able to use that helper method with the simple_form number field since it only takes a symbol and html options as arguments.

所以我在数据库中有一个精度为2的十进制字段,用来表示货币。除非最后一位小数以0结尾,否则它可以正常工作。799.90。当它在字段中显示时,它会将其剥离到799.9。我知道number_with_precision,但是我还不能使用simple_form number字段的helper方法,因为它只接受符号和html选项作为参数。

I figured then that I would need to create a custom input to extend simple_form's default number_field, but the syntax doesn't seem to be well documented, so I haven't been able to figure out how I might call number_with_precision in the definition of this custom input.

我当时想,我需要创建一个自定义输入来扩展simple_form的默认number_field,但是语法似乎没有得到很好的文档说明,所以我还没有弄清楚如何在这个自定义输入的定义中调用number_with_precision。

I essentially want to do what the OP of this question Formtastic number field with decimal precision? wanted with formtastic. Thanks!

本质上,我想要做的是这个问题的OP格式数字段的小数精度?希望与formtastic。谢谢!

1 个解决方案

#1


30  

If you can do it with formtastic you can usually do it with Simple Form in my experience. Try this:

如果你可以用formtastic来做,你通常可以用简单的Form来做。试试这个:

<%= f.input :sales_price, :input_html => {value: number_with_precision(f.object.sales_price, precision: 2) } %>

If using an input_field, then you don't need the :input_html:

如果使用input_field,则不需要:input_html:

<%= f.input_field :sales_price, value: number_with_precision(f.object.sales_price, precision: 2) %>

#1


30  

If you can do it with formtastic you can usually do it with Simple Form in my experience. Try this:

如果你可以用formtastic来做,你通常可以用简单的Form来做。试试这个:

<%= f.input :sales_price, :input_html => {value: number_with_precision(f.object.sales_price, precision: 2) } %>

If using an input_field, then you don't need the :input_html:

如果使用input_field,则不需要:input_html:

<%= f.input_field :sales_price, value: number_with_precision(f.object.sales_price, precision: 2) %>