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

0

The rule is not working. I get a value in Reals with the "," and I want to replace 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 decimal places, 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;  
}  

}  
?>  
    
asked by anonymous 17.12.2015 / 15:58

1 answer

0

The field where you enter this value must be set to Mysql as float , not int .

It's also important to remember that in this case you're getting string , not float .

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

$valorDespesa = (float) str_replace(",", ".", $check['valor_despesa']);  
    
17.12.2015 / 16:03