Calculation with PHP decimal number

3

I am making a query, which gets 2 values from the database. It returns the correction values with commas. But when multiplying is done, it is not counting the decimal places.

foreach ($compra['CompraItem'] as $valores) {                       
    $cotacao = $modeloMoedaCotacao->find('first', array('conditions'=>array(
        'MoedaCotacao.moeda_id' => $valores['moeda_id'],
        'MoedaCotacao.data' => date("Y-m-d"),
    ), array(
        'limit' => 1,
    )));
    echo $cotacao = FloatFromSQL($cotacao['MoedaCotacao']['cotacao']);
    echo '<br />';                                                
    echo $valor = FloatFromSQL($valores['valor']);
    echo '<br />';                                                
    $valorTotal = $valor * $cotacao;
    echo $valorTotal;
    echo '<br />';                                                
}  

Return:

5.14000 1980.00 = multiplication returns without using the decimal > > 9900

3.23000 160.00 = multiplication returns without using the decimal> > 480

5.14000 70.00 = multiplication returns without using the decimal> > 350

    
asked by anonymous 23.06.2015 / 17:07

2 answers

1

If you are going to work with calculations I often advise you to use a function that can format these values.

Example:


function valor_func($aValor, $aTipo, $a_dec = 2) { // valores com mascara e sem mascara
   switch ($aTipo):
      case 'C':// com mascara
         $valor = number_format(round($aValor, $a_dec), $a_dec, ',', '.');
         break;

      case 'S':// sem mascara
         $valor = str_replace(',', '.', str_replace('.', '', $aValor));
         break;

      case 'A':// arrendonda
         $valor = round($aValor, $a_dec);
         break;
      case 'D':// Decimais sem arredonda,sem mascara
         $posPonto = strpos($aValor, '.');
         if ($posPonto > 0):
            $valor = substr($aValor, 0, $posPonto) . '.' . substr($aValor, $posPonto + 1, $a_dec);
         else:
            $valor = $aValor;
         endif;
         break;
   endswitch;
   return $valor;
}

To show the values for the user use type 'C' and to calculate use type 'S' example:


$a = "5,14000"; // com mascara

echo valor_func($a,'S');// 5.14000 sem mascara
echo valor_func($a,'C');// 5,14000 com mascara

    
23.06.2015 / 18:30
1

The problem is that we use the comma as decimal separator , in PHP the decimal separator is the point .

Having said that you have N ways to solve your problem, from bringing those formatted numbers with . point of your database or converting to PHP

<?php
$a = "5,14000";
$b = "1980,00";

$a = floatval(str_replace(",", ".", $a));
$b = floatval(str_replace(",", ".", $b));

var_dump($a*$b);

If you are using PHP in version greater than 5.3 and have intl installed you can use the NumberFormatter .

    
23.06.2015 / 17:53