Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.3.4 possible bug in round() function using PHP_ROUND_HALF_DOWN mode

Tags:

php

rounding

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.

like image 594
wamarante Avatar asked Dec 26 '22 21:12

wamarante


1 Answers

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
like image 80
uzyn Avatar answered Feb 22 '23 23:02

uzyn