-1

The code below generates two random decimal values, then subtracts them to get $c.

The do-while loop is trying to ensure that $c will not be a whole number. But I keep getting times where $c actually is a whole number.

        do{
            unset($a);
            unset($b);
            unset($c);
            unset($adjuster);
            unset($c_is_int);

            $a = mt_rand(5, 75);
            $b = mt_rand(5, 75);
            $adjuster = mt_rand(2, 20);

            $decimal_selector = mt_rand(1, 6);
            if ($decimal_selector == 1){
                $a = $a / 10;
                $b = $b / 10;
            }
            if ($decimal_selector == 2){
                $a = $a / 10;
                $b = $b / 100;
            }
            if ($decimal_selector == 3){
                $a = $a / 100;
                $b = $b / 10;
            }
            if ($decimal_selector == 4){
                $a = $a / 100;
                $b = $b / 100;
            }
            if ($decimal_selector == 5){
                $a = $a / 1000;
                $b = $b / 1000;
            }
            if ($decimal_selector == 6){
                $a = $a / 1000;
                $b = $b / 100;
            }

            if($b < $a){
                $b = $b + ($a - $b) + $adjuster;
            }

            $c = $b - $a;

            if(intval($c) == $c) {
                $c_is_int = 1;
            } else {
                $c_is_int = 0;
            }

echo $a . '<br><br>';
echo $b . '<br><br>';
echo intval($c) . '<br>';
echo $c_is_int . '<br>';
echo $c . '<br><br>';
        } while($c_is_int == 1);

The attached image shows the results of one of these failing times. Any ideas on where this is going wrong?

enter image description here

gtilflm
  • 1,389
  • 1
  • 21
  • 51
  • It's still not clear what the purpose of your code is. Not implausible that you're looking for e.g. [arbitrary precision math](http://www.php.net/manual/en/book.bc.php) though instead of float/int juggling. – mario Dec 04 '13 at 02:04

2 Answers2

0

Why not check to see if the number has a decimal?

$c = 123.456;

if(strpos((string) $c, '.') !== FALSE) {
    // is decimal/float/double
}

You can also just check to see if it's an int

if(is_int($c))
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • I originally tried `is_int()`, but it kept failing for some reason (http://stackoverflow.com/questions/20364384/double-integer-php/20364537) – gtilflm Dec 04 '13 at 02:02
0

You want to keep in mind that the integer 3 and float 3.0 will compare as equal when using the ==.

Consider:

$c_is_int = $c == floor( $c );
...
while( $c_is_int )
Matt R. Wilson
  • 7,268
  • 5
  • 32
  • 48