Numbers are not adding up correctly

0

I'm doing a search on MongoDB and bringing the sum of some values. It correctly brings the values that are there by adding them up. The problem is being when I need to, for example, get the value 1 and add it with the value 2. I have 2 numbers as an example:

Valor 1: 980
Valor 2: 2.094

And the sum of this result is giving 982.094 and it would be 3,074 .

The code I use:

$queryReceitaMeta = $this->mongo_db->aggregate('metas_receita', $aggregate);

  if(count($queryReceitaMeta['result']) > 0){

    $rowQueryReceitaMeta = $queryReceitaMeta['result'][0];

    foreach($meses as $mes){

      $totalReceitaMeta += $rowQueryReceitaMeta['soma_'.$mes];
    }
  }

In this code it adds the result of the whole year, which adds up each month (January-December).

  

When I hit the "." (point) of the values, then it adds up right. Using the   function str_replace it works normally.

    
asked by anonymous 13.03.2017 / 23:44

1 answer

3

This happens because, by default, PHP considers the . character as the separator of the decimal part, which is the default in the US, for example.

We wrote 1,234.00 to represent the number one thousand two hundred and thirty-four, already they write 1,234.00. So the number 2.094, instead of being considered two thousand, is two ninety-four hundredths.

Just check:

$a = 2.094;
$b = 3;

if ($a > $b) {
  echo "$a é maior que $b";
} else {
  echo "$a é menor que $b";
}

The result will be:

2.094 é menor que 3 

So to get around this you really need to remove . from the value, since PHP does not have a character that divides the thousands. To represent the value 2.094 you must have $value = 2094 .

If at the end you want to display the value with the appropriate separations, you can use the number_format :

$a = 2.094;
$b = 980;

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

$c = $a + $b;

echo number_format($c, 2, ',', '.');

The output is:

3.074,00
    
13.03.2017 / 23:58