Tony M
Tony M

Reputation: 341

Rails number_field that displays whole numbers if nothing to right of decimal

In my rails view, I've got the following code for a number field:

<div class="input-group">
    <%= f.number_field :percent, step: :any, :required => true, :class => 'percent-field', :placeholder => "Percent" %>
    <div class="input-group-append">
    <span class="input-group-text">%</span>
    </div>
</div>

My database is set to save these values as decimals, with a precision of 5 and a scale of 2. This is from my schema:

t.decimal "percent", precision: 5, scale: 2

If a user types a whole number in the number input field and saves that value, when they go back and try to edit that value it is showing a number with a decimal and one zero to the right of the decimal. So "30" becomes "30.0".

How can I get the input field edit view to display only the whole number, without a decimal, in cases where nothing is added to the right of the decimal?

Upvotes: 1

Views: 1628

Answers (2)

widjajayd
widjajayd

Reputation: 6253

you can pass previous value to :value and give it the format like this code below

<div class="input-group">
    <%= f.number_field :percent, step: :any, :required => true, :class => 'percent-field', :placeholder => "Percent", :value => number_with_precision(f.object.percent,precision: 2,  strip_insignificant_zeros: true) %>
    <div class="input-group-append">
    <span class="input-group-text">%</span>
    </div>
</div>

Upvotes: 4

Semih Arslanoglu
Semih Arslanoglu

Reputation: 1129

You can use strip_insignificant_zeros helper as explained here.

It's basically converting your float to integer if ending is .0

Upvotes: 1

Related Questions