Note that there are some explanatory texts on larger screens.

plurals
  1. POInteger check in PHP
    primarykey
    data
    text
    <p>I'm writing an odds converter in PHP and came across <a href="http://www.sitepoint.com/forums/showthread.php?608881-Converting-Decimal-to-Fractions" rel="nofollow">this</a> code for converting decimal odds to fractional ones</p> <pre><code>function dec2frac($dec) { $decBase = --$dec; $div = 1; do { $div++; $dec = $decBase * $div; } while (intval($dec) != $dec); if ($dec % $div == 0) { $dec = $dec / $div; $div = $div / $div; } return $dec.'/'.$div; } </code></pre> <p>When I tested the code, it would sometimes succeed in the calculations and sometime try to load the page for some time without success so I figured that it got stuck in the loop somehow. I set the time limit to 1 second and an echo in the loop, which confirmed my suspicion. I added these two echoes to the loop so I could see what went wrong.</p> <pre><code>echo "$dec $div&lt;br/&gt;"; echo var_dump(intval($dec) == $dec)." $dec is int&lt;br/&gt;"; </code></pre> <p>Example printout when it fails, using decimal = 1.6</p> <p>1.2 2<br> bool(false) 1.2 is int<br> 1.8 3<br> bool(false) 1.8 is int<br> 2.4 4<br> bool(false) 2.4 is int<br> 3 5<br> bool(false) 3 is int //should break here and return 3/5<br> 3.6 6<br> bool(false) 3.6 is int<br> 4.2 7<br> bool(false) 4.2 is int</p> <p>Example printout when it succeeds, using decimal = 1.8</p> <p>1.6 2<br> bool(false) 1.6 is int<br> 2.4 3<br> bool(false) 2.4 is int<br> 3.2 4<br> bool(false) 3.2 is int<br> 4 5<br> bool(true) 4 is int </p> <p>Why doesn't it recognize the integers sometimes? How can I fix it so it exits the loop when an integer is found?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload