Rule in model using str_replace() to replace "," with "."

Asked

Viewed 50 times

0

The rule is not working. I take a real value with "," and want to replace it with "." to save the decimal values in the bank. For example, the value 35.39 reais would be 35.39 in the bank. The rule does not work and the value loses the decimals, only getting 35.00 in the bank.

Controller:

<?php  

public function inserirDespesa() {  
    if ($this->request->isPost()) {  

//carrega model  
$this->loadModel('Despesa');  

if ($this->Despesa->save($this->request->data)) {  

$this->Session->setFlash("Despesa inserida");     
}  
}  

}  
?>  

Model:

<?php  

class Despesa extends AppModel {  

    public $name='despesa';  
    public $useTable='despesas';  
    public $primaryKey='id_despesa';  

public $validate=array(  
'valor_despesa'=>array(  
'preco'=>array(  
'rule'=>'preco')));  

    public function preco($check) {  
$valorDespesa=0;  

$valorDespesa=str_replace(",", ".", $check['valor_despesa']);  

return true;  
}  

}  
?>  

1 answer

0

The field where you enter this value must be configured in Mysql as float, and not as int.

It is also important to remember that in this case you are getting one string, and not a value float.

Try to give a cast for float to see if this works:

$valorDespesa = (float) str_replace(",", ".", $check['valor_despesa']);  
  • The problem is that the "," is not replaced by ",". The format in the database is decimal

Browser other questions tagged

You are not signed in. Login or sign up in order to post.