Advertisement
jessicakennedy1028

Decimal to Fraction

Sep 9th, 2018
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.95 KB | None | 0 0
  1. function decimal_to_fraction($float) {
  2.     $float = clean_number($float);
  3.     $whole = floor($float);
  4.     $decimal = $float - $whole;
  5.     $leastCommonDenom = 384; // 128 * 3;
  6.     $denominators = array (2, 3, 4, 8, 16, 24, 48, 64, 128);
  7.     $roundedDecimal = round ($decimal * $leastCommonDenom) / $leastCommonDenom;
  8.     if ($roundedDecimal == 0) return $whole;
  9.     if ($roundedDecimal == 1) return $whole + 1;
  10.     foreach ( $denominators as $d ) {
  11.         if ($roundedDecimal * $d == floor ($roundedDecimal * $d)) {
  12.             $denom = $d;
  13.             break;
  14.         }
  15.     }
  16.     return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
  17. }
  18.  
  19. /* Example */
  20.     echo decimal_to_fraction(.5).'<br />';
  21.     echo decimal_to_fraction(.25).'<br />';
  22.     echo decimal_to_fraction(.75).'<br />';
  23.     echo decimal_to_fraction(.125).'<br />';
  24.     echo decimal_to_fraction(.3046875).'<br />';
  25.  
  26. /* Output */
  27. 1/2
  28. 1/4
  29. 3/4
  30. 1/8
  31. 39/128
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement