PHP - Summing an array of decimal values

2019-08-11 08:34发布

I'm trying to calculate the sum of an array of decimal values in PHP, but for some reason it keeps rounding to integers.

for example:

$oldArray = array(0.00,1000.11,988.92,978.22,964.01,953.07,948.82,917.26,902.56,913.21,904.08,898.86,892.79);
$myVar = 0.0;
for($k=1;$k<10;$k++)
{
$myVar += $oldArray[$k];
}
print_r($myVar);

$oldArray is actually populated with decimal values from an SQL query (the length of $oldarray is about several hundred, but I want the first 10. In the above example, I'm expecting $myVar to be a decimal, but it turns out to be just an integer. I tried setting $myVar = 0.0000 before the for loop, I tried $myVar += $oldArray[$k] + 0.0000, etc but nothing seems to work.

What am I doing wrong? How do I explicitly set $myVar to be a decimal?

4条回答
Anthone
2楼-- · 2019-08-11 08:55

You can try using array_sum() instead and use (float) to cast the values. Additionally I would make sure that the values in the array are in the correct format (1.45 and not 1,45). HTH.

Update

Btw. you can use "is_float()" to check every parameter in the array.

查看更多
爷、活的狠高调
3楼-- · 2019-08-11 08:56

Given that this seems impossible to reproduce, to me it sounds like a problem with your PHP environment itself.

Check php.ini for a setting called "precision", and make sure it's set to the default of 14 significant figures. I can't imagine why this would be changed, but it would definitely have an impact.

查看更多
劫难
4楼-- · 2019-08-11 09:09

Can't reproduce this.

php > $oldArray = array(0, .1, .2, .3, .4, .5, .6, .7, .8, .9);                                                    
php > $myVar = 0.0;
php > for($k=0;$k < count($oldArray);$k++)
php > {
php { $myVar += $oldArray[$k];
php { }
php > print_r($myVar);
4.5

EDIT: I tried the code in your comment, and it's fine. Like AlbertoPL, I suspect the problem is elsewhere.

php > $oldArray = array(0.01,1000.11,988.92,978.22,964.01,953.07,948.82,917.26,902.56,913.21,904.08,898.86,892.79);
php > $myVar = 0.0000;
php > for($k=1;$k<10;$k++)
php >   $myVar += $oldArray[$k];
php > print_r($myVar);
8566.18
查看更多
▲ chillily
5楼-- · 2019-08-11 09:13

Make your own implementation:

function sum_array($arr){
 $count = 0;
  foreach ($arr as $val){
    if (!is_numeric($val) // neglect any non numeric values
      {
        $error = true;
        continue;
      }
      else{
        $count = $count + ($val*1); //casting to numeric if the value supplied as string
      }
  }
  return $count
}

echo sum_array($myArray);
查看更多
登录 后发表回答