数值意外向下舍入
我有一个循环计算几个收入值,然后将它们加在一起,如下所示:
$SalesGrowth = $C2012Sales+$C2011Sales;
在某些情况下,这有效,并且我得到了预期的结果,例如: 761.9 + 759.0 = 1520.9
在其他情况下,PHP 似乎随机决定错误地舍入(??) 并更改单位 (??),我得到:
8,788.0 + 8,794.3 = 16
这是怎么回事?我什至尝试回显由空格分隔的单独销售值,并且它们显示正确,因此基本数字没有错误。
I have a loop that calculates a couple revenue values then adds them together, like this:
$SalesGrowth = $C2012Sales+$C2011Sales;
In some cases, this works, and I get the expected, e.g.: 761.9 + 759.0 = 1520.9
In others, it looks like PHP randomly decides to round incorrectly (??) AND change the units (??) and I get:
8,788.0 + 8,794.3 = 16
What is going on here? I've even tried echoing out the separate sales values separated by a space, and they show up correctly, so the underlying figures aren't wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
解释为数字时,
8,788.0
就是8
,解析在逗号处停止。如果您想允许像千位分隔符这样的花招,您将需要一些区域设置感知的数字解析。
更新:如果您有Zend Framework,您可以这样做:
您可以尝试从环境中获取它,而不是对区域设置进行硬编码:
new Zend_Locale(setlocale(LC_ALL, ""))
Interpreted as a number,
8,788.0
is just8
, and parsing stops at the comma.You'll need some locale-aware number parsing if you want to allow gimmicks like thousands-separators.
Update: If you have the Zend Framework, you can do this:
Instead of hard-coding the locale, you could try and take it from the environment:
new Zend_Locale(setlocale(LC_ALL, ""))
伙计,逗号问题......
在添加数字之前删除数字中的所有逗号......
Dude the comma issue....
remove all the commas from the numbers before adding them...
这非常简单...当您要求 PHP 使用
+
运算符时,它会隐式地将这些字符串(例如"8,788.0"
)转换为数值。由于您有一个,
字符,因此它终止了数字的有用性,并导致它被解释为8
。依此类推...去掉非
[0-9.]
字符,效果会更好。This is pretty simple... When you ask PHP to use the
+
operator, it will implicitly convert these strings such as"8,788.0"
to an numeric value. Since you have a,
character, it terminates the usefulness of the number, and it results in it being interpreted as8
. And so on...Get rid of the non
[0-9.]
characters and it will work better.请注意,761.9 是有效数字,而 8,788.0 则不是(从 PHP 的角度来看)。
因此,数字上下文中的
8,788.0
将计算为 8,就像8,794.3
一样。 8+8 = 16。要解决此问题,请处理数据以使数字格式正确。
Notice that 761.9 is a valid number, while 8,788.0 is not (from PHP's point of view).
So
8,788.0
in number context will evaluate as 8, just like8,794.3
. And 8+8 = 16.To fix this problem, process your data to make numbers formatted properly.