在rails number_field中四舍五入

时间:2019-01-04 19:41:59

标签: ruby-on-rails validation ruby-on-rails-4 input display

因此我有一个number_field:

<?php

    include ("functions.php");
    session_start();

    $username=$_POST['username'];
    $password=$_POST['password'];
    $password2=$_POST['password2'];
    $nome=$_POST['nome'];
    $dataNas=$_POST['dataNas'];
    $email=$_POST['email'];
    $telemovel=$_POST['telemovel'];

    if(!$username || !$password || !$password2 || !$nome || !$dataNas || !$email || !$telemovel )
    {
        echo 'missing fields;
        exit;
    }
    else {
    $insere="INSERT INTO clientes (`username`, `password`, `nome`, `dataNas`, `email`, `telemovel` ) VALUES ('".$username."', '".$password."', '".$nome."', '".$dataNas."', '".$email."', '".$telemovel."')";
    $resultado=DBExecute($insere);

    if($resultado==1){
        echo'<p>Registo efetuado com sucesso<br/>';
        header("location:mercadorias.html");
    }
    else 
        echo '<p>Dados não inseridos<br/>';
}
?>

我输入值1.1,保存并刷新,它显示值“ 1.100000023841858”。我了解这是因为基础数据库字段是浮点数,并且我可以将数据库字段更改为十进制,但是没有其他方法来控制number_field的显示格式吗?

2 个答案:

答案 0 :(得分:1)

答案是:

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

答案 1 :(得分:0)

对于价格,您可以这样:

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

此外,您可以通过将活动记录获取器添加到模型文件中来覆盖它:

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