Re: Math problem with modulus

From: Date: Tue, 05 Oct 2004 12:00:35 +0000
Subject: Re: Math problem with modulus
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-198656@lists.php.net to get a copy of this message
Christoph Schwadorf wrote:
Hello. I have some problems with basic math in the function below. function Custom_Round($Digit, $Divisor) {
    return (($Digit / $Divisor) - (($Digit % $Divisor) / $Divisor));
} Custom_Round(23, 10) returns float(2) as expected. Same for Custom_Round(22, 10). BUT when you compare the both results like below Custom_Round(23, 10)!=Custom_Round(22, 10) I always get bool(true) whereas the result should be bool(false) When I have debuged this small piece of code I found out that intval(Custom_Round(23, 10)) = 1 whats definitly not expected. But intval(Custom_Round(22, 10)) = 2 as expected. Replacing Custom_Round() by Floor() works fine, but why does the custom function doing the same not work? Is this a bug in PHP? This problem occurse in PHP 4.3.3 and PHP 5.0.1. Thanks for help, Christoph intval converts other types to integers. Integers can only be whole numbers, eg 1, 2, 15, -789, etc. No matter what decimals, intval converts it to the lower (closer to 0) integer value. Eg 2.5 => 2, 19.9=>19, -25.3 => -25 etc.
What happens now is that you're converting a float to an integer, float=>integer conversion has a lot of "problems", floating point numbers have a lot more precision. Numbers given as being float(2) can actually be something of the like 1.99999999999999999999999999999999999999, and when converted to intgers, they drop down to 1 instead of 2. This is explained here: http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting.from-float

« previous php.general (#198656) next »