Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify decimal precision in a simple_form number field (Rails)

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.

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.

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

like image 848
wisew Avatar asked Jul 09 '12 18:07

wisew


People also ask

What is precision in decimal number?

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2. In SQL Server, the default maximum precision of numeric and decimal data types is 38.

What is precision in rounding?

Precision of a numeric value describes the number of digits that are used to express that value, including digits to both the left and the right of any decimal point. For example 4.520 has a precision of 4. Zuora supports up to 13 digits to the left of the decimal place, and up to 9 digits to the right.


1 Answers

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

<%= 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:

<%= f.input_field :sales_price, value: number_with_precision(f.object.sales_price, precision: 2) %>
like image 185
toxaq Avatar answered Oct 14 '22 00:10

toxaq