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?
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.
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.
Can't reproduce this.
EDIT: I tried the code in your comment, and it's fine. Like AlbertoPL, I suspect the problem is elsewhere.
Make your own implementation: