Page 1 of 1
Problem with rounding in intval
Posted: Tue Mar 24, 2009 12:00 pm
by jmashore
In this example, $answer_01 = 175 and $answer_02 = 174...any ideas why ? I'm sure this is some totally obvious answer, but it doesn't make since to me.
Any help would be appreciated.
Code: Select all
$price = .0875;
$divisor = .0005;
$answer_01 = (float)($price/$divisor);
$answer_02 = intval($answer_01);
echo $answer_01 . "<br>";
echo $answer_02;
Re: Problem with rounding in intval
Posted: Tue Mar 24, 2009 12:17 pm
by wellhole
The value in $answer_01 is a float value. It may actually be 174.999999 because floats are not exact. intval() will take the integer part of it which is 174. You should consider casting the value to (int)$answer_02 or perhaps use ceil($answer_02) or round($answer_02). Please test these first because I haven't.
See the references at
http://us3.php.net/manual/en/function.round.php
Re: Problem with rounding in intval
Posted: Tue Mar 24, 2009 12:39 pm
by jmashore
This problem is resolved for this application. Using the (int) cast was ineffective. The goal being to establish whether $price was evenly divisable by $divisor. Thanks to all those that made suggestions. The resolution is as follows:
Code: Select all
$price = .0875; // This could be any number
$divisor = .0005; // This can be any number
$answer_01 = (float)($price/$divisor);
$answer_02 = ceil($answer_01);
if ($answer_01 != $answer_02){
echo "$price is NOT divisable by $divisor";
}else{
echo "$price is evenly divisable by $divisor";
}
Re: Problem with rounding in intval
Posted: Tue Mar 24, 2009 12:52 pm
by wellhole
I don't think division guarantees 2 / 2 = 0.999999. You might get 2 / 2 = 1.000001. ceil() on each of those will produce 2 different values.
Re: Problem with rounding in intval
Posted: Tue Mar 24, 2009 1:03 pm
by mmoussa
jmashore wrote:This problem is resolved for this application. Using the (int) cast was ineffective. The goal being to establish whether $price was evenly divisable by $divisor.
If that's all you need to do, then why not use the modulus operator?
Code: Select all
if ( $price % $divisor == 0 )
{
// do stuff that you do when they are evenly divisible
}
else
{
// do stuff that you do when they are not
}
Re: Problem with rounding in intval
Posted: Tue Mar 24, 2009 1:06 pm
by wellhole
mmoussa wrote:If that's all you need to do, then why not use the modulus operator?
Mod doesn't work with floats. Perhaps ceil() may very well be the best option. Let's just hope 2 / 2 will always be .999999 and never 1.000001.