[英]PHP 5.3.4 possible bug in round() function using PHP_ROUND_HALF_DOWN mode
Unless I have misunderstood how round() function works in PHP, I think there is a bug in it: 除非我误解了round()函数在PHP中是如何工作的,否则我认为它有一个错误:
Example: 例:
Running: 运行:
$prod = 201.6 * 0.000275;
echo "No Round..: " . $prod;
echo "With Round: " . round($prod, 2, PHP_ROUND_HALF_DOWN);
PHP Returns: PHP返回:
No Round..: 0.05544
With Round: 0.06
What I expect: 我期待的是:
With Round, I expected 0.05 as a result. 有了Round,我预计会有0.05的结果。 Is this expected result right? 这个预期结果对吗?
Enviroment: 环境:
PHP 5.3.4 running on Windows 7 64bits with Apache 2.2.17. PHP 5.3.4使用Apache 2.2.17在Windows 7 64位上运行。
Tnks a lot. 很多。
That is the correct expected result. 这是正确的预期结果。
PHP_ROUND_HALF_DOWN
only comes into play when the value is exactly at half, for your case that would be 0.055. PHP_ROUND_HALF_DOWN
仅在值恰好为一半时发挥作用,对于您的情况为0.055。
Anything more than 0.055, eg. 超过0.055的任何东西,例如 0.0550000001, would result in 0.06. 0.0550000001,将导致0.06。
If you prefer to round down, you should try floor()
. 如果您想要向下舍入,则应尝试使用floor()
。
<?php
$prod = 201.6 * 0.000275;
$prod = floor($prod * 100)/100;
echo $prod; // gives 0.05
That's because PHP doesn't track overflows. 那是因为PHP不跟踪溢出。
For example, try also 例如,尝试一下
print (int) ((0.1 + 0.7) * 10);
You would expect that the expression returns 8, but prints 7 instead. 您可能希望表达式返回8,而是打印7 。 This happens because the result of simple arithmetic expression is stored internally as 7.999999 instead 8 and when PHP casts the number to int it simply truncate the fractional part. 发生这种情况是因为简单算术表达式的结果在内部存储为7.999999而不是8 ,当PHP将数字转换为int时,它只是截断小数部分。 It means a 12,5% error! 这意味着12.5%的错误!
Use BCMath extension instead if you need precise calculations. 如果需要精确计算,请使用BCMath扩展。
Check out the Zend PHP 5 Certification Study Guide (php|architect) at the chapter "PHP Basics". 在“PHP基础知识”一章中查看Zend PHP 5认证学习指南 (php |架构师)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.