PHP 5.3.4 possible bug in round() function using PHP

Unless I have misunderstood how round() function works in PHP, I think there is a bug in it:

Example:

Running:

$prod = 201.6 * 0.000275;  
echo "No Round..: " . $prod;  
echo "With Round: " . round($prod, 2, PHP_ROUND_HALF_DOWN);  

PHP Returns:

No Round..: 0.05544  
With Round: 0.06

What I expect:
With Round, I expected 0.05 as a result. Is this expected result right?

Enviroment:
PHP 5.3.4 running on Windows 7 64bits with Apache 2.2.17.

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.

Anything more than 0.055, eg. 0.0550000001, would result in 0.06.

If you prefer to round down, you should try 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.

For example, try also

print (int) ((0.1 + 0.7) * 10);

You would expect that the expression returns 8, but prints 7 instead. 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. It means a 12,5% error!

Use BCMath extension instead if you need precise calculations.

Check out the Zend PHP 5 Certification Study Guide (php|architect) at the chapter "PHP Basics".

链接地址: http://www.djcxy.com/p/57746.html

上一篇: CakePHP默认的flash并不总是呈现

下一篇: 使用PHP的round()函数中的PHP 5.3.4可能的错误