PHP - 总结一个十进制值的数组 [英] PHP - Summing an array of decimal values

查看:166
本文介绍了PHP - 总结一个十进制值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算在PHP中的十进制值的数组的总和,但由于某种原因,它保持四舍五入到整数。



例如: p>

  $ 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; ($ k = 1; $ k< 10; $ k ++)

$ myVar + = $ oldArray [$ k];

}
print_r($ myVar);

$ oldArray实际上是用SQL查询中的十进制值填充的($ oldarray的长度大约是几个百,但我想第一个10.
在上面的例子中,我期待$ myVar是一个十进制,但它只是一个整数,我试图设置$ myVar = 0.0000 for循环,我试过$ myVar + = $ oldArray [$ k] + 0.0000等,但似乎没有任何工作。

我做错了什么?如何显式设置$ myVar是一个小数?

解决方案

鉴于这似乎是不可能重现,对我来说这听起来像是一个问题,您的PHP环境本身。



检查php.ini中的一个名为precision的设置,并确定它被设置为14位有效数字的默认值。被改变,但肯定会有影响。


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?

解决方案

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.

这篇关于PHP - 总结一个十进制值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆