Majiy
Majiy

Reputation: 1920

PHP round() returns unexpected value

I have a double value of 2.6647 which I am trying to round mathematically correct to 2 decimal places.

I am expecting a return value of 2.67.

7 (the last decimal place) should round 4 (the second-last decimal place) up to 5, 5 should round 6 (the third-last decimal place) up to 7.

$value = 2.6647;
echo round( $value, 2, PHP_ROUND_HALF_UP );

But instead I receive 2.66. Why is this happening?

PHP Version is 5.3.28.

Upvotes: 0

Views: 297

Answers (4)

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Please take a look this..

In round function

echo round(2.6647, 2);  // 2.66
echo round(2.6637, 2);  // 2.66
echo round(2.6657, 2);  // 2.67
echo round(2.6667, 2);  // 2.67

If third decimal place is 5 or greater than 5 then one incremented at second position.

Upvotes: 0

Mark Miller
Mark Miller

Reputation: 7447

You are misunderstanding how round() works:

"7 (the last decimal place) should round 4 (the second-last decimal place) up to 5, 5 should round 6 (the third-last decimal place) up to 7."

This is incorrect.

round() only considers the number following the specified decimal places. So in this case, the 7 is not considered at all. Only the 4 is considered, which, being less than 5, determines that the number is rounded to 2.66.

To get the logic as you specified in the quote above, you would need to do something like this:

$value = 2.6647;
$value2 = round( $value, 3, PHP_ROUND_HALF_UP ); // 2.665
echo round( $value2, 2, PHP_ROUND_HALF_UP ); // 2.67

which is probably not a very feasible way to do things, but should give a better idea of how round() is working.

Upvotes: 0

pavel
pavel

Reputation: 27082

Rounding to n decimals is driven by n+1th decimal. In this case the third one decimal is 4, so the number is rounded down to 2.66.

Upvotes: 1

user2681045
user2681045

Reputation: 390

47 < 50

So 2.6647 will be rounded off to 2.66 irrespective of the last parameter.

Upvotes: 2

Related Questions