【问题标题】:Rails number_field that displays whole numbers if nothing to right of decimalRails number_field,如果小数点右边没有,则显示整数
【发布时间】:2020-02-13 21:22:21
【问题描述】:

在我的 rails 视图中,我有一个数字字段的以下代码:

<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>

我的数据库设置为将这些值保存为小数,精度为 5,小数位数为 2。这是来自我的架构:

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

如果用户在数字输入字段中输入一个整数并保存该值,当他们返回并尝试编辑该值时,它会显示一个带有小数点且小数点右侧有一个零的数字。所以“30”变成了“30.0”。

如果小数点右侧没有添加任何内容,如何让输入字段编辑视图仅显示整数而不显示小数点?

【问题讨论】:

    标签: html ruby-on-rails


    【解决方案1】:

    您可以将先前的值传递给 :value 并为其提供如下代码的格式

    <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>
    

    【讨论】:

      【解决方案2】:

      您可以按照here 的说明使用 strip_insignificant_zeros 帮助器。

      如果结尾是 .0,它基本上会将您的浮点数转换为整数

      【讨论】:

        猜你喜欢
        • 2016-02-09
        • 1970-01-01
        • 1970-01-01
        • 2012-10-23
        • 2017-04-08
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        相关资源
        最近更新 更多