四舍五入 rails number_field

Rounding in a rails number_field

我有一个 number_field 因此:

<%= ff.number_field :total_cost_savings, {class: 'form-control number', :step => 0.01} %>

我输入值 1.1,保存并刷新,它显示值“1.100000023841858”。我知道这是因为底层数据库字段是浮点数,我可以将数据库字段更改为小数,但是没有某种方法可以控制 number_field 的显示格式吗?

对于价格你可以这样做:

    f.number_field :total_cost_savings, value: number_to_currency(f.object.total_cost_savings, delimiter: '', unit: ''), step: 0.01

此外,您可以通过将此添加到您的模型文件来覆盖活动记录 getter:

    def total_cost_savings
      read_attribute(:total_cost_savings).round(2)
    end      

答案是:

<%= ff.number_field :total_cost_savings, {value: number_with_precision(ff.object.total_cost_savings, precision: 2), class: 'form-control number', :step => 0.01} %>