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

15,371

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) %>
Share:
15,371

Related videos on Youtube

wisew
Author by

wisew

Updated on September 16, 2022

Comments

  • wisew
    wisew over 1 year

    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!

  • wisew
    wisew almost 12 years
    No luck. The value is loaded correctly, but the precision isn't respected if the last decimal place is 0. Any idea how I might be able to force it to display the 0 without resorting to JavaScript?
  • toxaq
    toxaq almost 12 years
    Have you tried just doing <%= number_with_precision(5, :precision => 2) %> ? My example and that both format correctly, it sounds like you've got something weird going on.
  • wisew
    wisew almost 12 years
    I figured out where I went wrong - since I was using f.input_field, I didn't have to pass value: number_with_precision... in the input_html hash – I could just set it directly. It works now - thanks!
  • jmarceli
    jmarceli about 9 years
    IMPORTANT! If you are using locale which has comma as default separator you must specify dot as separator because comma support for new HTML5 number inputs (used by simple_form) is not good enough (aeyoun.com/posts/html5-input-number-localization.html)