[ACCEPTED]-PHP - Summing an array of decimal values-sum
Given that this seems impossible to reproduce, to 6 me it sounds like a problem with your PHP 5 environment itself.
Check php.ini for a setting 4 called "precision", and make sure it's set 3 to the default of 14 significant figures. I 2 can't imagine why this would be changed, but 1 it would definitely have an impact.
You can try using array_sum() instead and use (float) to 5 cast the values. Additionally I would make 4 sure that the values in the array are in 3 the correct format (1.45 and not 1,45). HTH.
Update
Btw. you 2 can use "is_float()" to check 1 every parameter in the array.
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 2 in your comment, and it's fine. Like AlbertoPL, I 1 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
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);
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.