Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function decimal_to_fraction($float) {
- $float = clean_number($float);
- $whole = floor($float);
- $decimal = $float - $whole;
- $leastCommonDenom = 384; // 128 * 3;
- $denominators = array (2, 3, 4, 8, 16, 24, 48, 64, 128);
- $roundedDecimal = round ($decimal * $leastCommonDenom) / $leastCommonDenom;
- if ($roundedDecimal == 0) return $whole;
- if ($roundedDecimal == 1) return $whole + 1;
- foreach ( $denominators as $d ) {
- if ($roundedDecimal * $d == floor ($roundedDecimal * $d)) {
- $denom = $d;
- break;
- }
- }
- return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
- }
- /* Example */
- echo decimal_to_fraction(.5).'<br />';
- echo decimal_to_fraction(.25).'<br />';
- echo decimal_to_fraction(.75).'<br />';
- echo decimal_to_fraction(.125).'<br />';
- echo decimal_to_fraction(.3046875).'<br />';
- /* Output */
- 1/2
- 1/4
- 3/4
- 1/8
- 39/128
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement