How to format and calculate 1,000,000.00 in PHP?

1

Hello,

I have values like 1,000,000 that I need to add and then display. I'm doing this:

<?php
$vlgastoGeralDeFabricacao = str_replace(',', '.', $vlgastoGeralDeFabricacao);
$vlDepreciacao = str_replace(',', '.', $vlDepreciacao);
$vlgastoPessoalDeProducao = str_replace(',', '.', $vlgastoPessoalDeProducao);
$vlOutrosCustosIndiretos = str_replace(',', '.', $vlOutrosCustosIndiretos);

$custoIndireto = $vlgastoGeralDeFabricacao + $vlDepreciacao +   $vlgastoPessoalDeProducao + $vlOutrosCustosIndiretos;

echo number_format($custoIndireto,2,',','.');
?>

but this error always appears:

  

Notice: A well-formed numeric value encountered

and points to the echo line.

Otherwise the value of 185,700.00 is appearing as 185.70

    
asked by anonymous 14.09.2016 / 16:50

1 answer

3

Be very careful with values in the Brazilian format, you need to remove "." and instead of "," put "." ;

With str_replace where:

  • first parameter pass a search array;
  • second parameter pass an array of changes;
  • third parameter the value to be changed.
<?php    

  $v1 = "1.000,00";
  $v2 = "2.000,00";

  $vf1 = str_replace(['.',','],['','.'], $v1);
  $vf2 = str_replace(['.',','],['','.'], $v2);

  $vf  = $vf1 + $vf2;

  echo $vf; // saída sem formato 3000

  echo number_format($vf, 2, ',', '.'); //saída: 3.000,00

Then format again with number_format (% with%).

    
14.09.2016 / 17:04