Re: Math problem with modulus

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux