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

Asked

Viewed 114 times

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 that mistake always appears:

Notice: A non well Formed Numeric value encountered

and points to the echo line.

Besides that the value of 185.700,00 is appearing as 185,70

  • $vlgastoGeralDeFabricacao what is the initial value?

  • The value is 185.700,00

  • You mean, what is the amount of $cost? It’s supposed to be 804,230.00

  • before running this line $vlgastoGeralDeFabricacao = str_replace(',', '.', $vlgastoGeralDeFabricacao);´ qual é valor de $vlgastoGeralDeabricacao`?

  • The value is what I informed above @Virgilionovic, 185.700,00

  • These values are taken from a form.

  • So you can come like this: 1.000,00?

  • No, because that way 1,000.00 is not added up, php does not compute monetary values with "," comma.

  • Try this way; add all numbers (without using str_replace) and then show off with the number_format and see what comes up.

Show 5 more comments

1 answer

3


Take great care with values in Brazilian format, need to remove the "." and in place of "," put the ".";

With str_replace where:

  • first parameter passes a query array;
  • second parameter pass a change array;
  • 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

and finally format again with number_format ( number_format($vf, 2, ',', '.') ).

Browser other questions tagged

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