Numbers are not adding up correctly

Asked

Viewed 111 times

0

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

Valor 1: 980
Valor 2: 2.094

And the sum of that result is giving 982.094 which 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 he sums up the result of the whole year, being that he sums up each month (January-December).

When I take the "." (point) of the values, then it sums right. Using the function str_replace it works normally.

  • 1

    The . in the US and some other countries symbolizes the beginning of the decimal places, as well as the , in Brazil. I think the behavior is correct. I suggest you check the location (locale) options of your database and PHP to see if they are aligned.

  • I spent more time thinking about how it should be 3,074... The sum you want to make should be 0.980 + 2.094, that would be 3,074. If you want 3,074 (three thousand and seventy-four) you should omit the ., thus 980+2094. Add 980.000 + 3.074 will give 982.094, which is what you’re doing.

1 answer

3


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

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

Just check by doing:

$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 the . value, since PHP does not have a character that divides thousands. To represent the value 2.094 you need to have $value = 2094.

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

$a = 2.094;
$b = 980;

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

$c = $a + $b;

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

The exit is:

3.074,00

Browser other questions tagged

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