Rounding in PHP

Associate
Joined
18 Oct 2002
Posts
231
Whats the deal with PHP rounding?

I've tried 4.3.2 on a win2k IIS box and 4.4.2 on a win2k apache box, and seem to have strange results using round($x , 2):

27.115 goes to 27.12
27.125 goes to 27.13
125.245 goes to 125.25
125.244 goes to 125.24
37.535 goes to 37.53 <----- Errrr why?

It's not using bankers rounding, 5 is being treated as go up, but that last one is being odd.....bug?

Different version of PHP?
 
I was thinking it might be a precision problem, my issue is that I need it to match up with the calculations done by Visual Basic, which doesn't seem to have a precision problem with it's currency datatype. Hmm
 
That's doing it to bankers rounding which I don't want but yes the principle seems to work. I've tweaked it so if the 1/1000 position is 5 then change it to a 9 and then round, else just round. Playing with it now and so far so good......
 
With a bit of quick tinkering i've got this working, though it needs a tidy up and is probably quite slow.
Code:
function super_round($moneyfloat = null)
{
	$a = strpos($moneyfloat, ".");
	if ($a > 0) {
		$a = $a + 3;
		if (substr($moneyfloat,$a,1) == "5") {
			$moneyfloat = sprintf("%01.3f", $moneyfloat);
			$moneyfloat[$a] = "9";
		}
	}
	return round($moneyfloat,2);
}

37.535 = 37.54
37.533 = 37.53
37.53499999999 = 37.53
 
Back
Top Bottom