Search code examples
phpdecimalfractions

PHP convert decimal into fraction and back?


I want the user to be able to type in a fraction like:

 1/2
 2 1/4
 3

And convert it into its corresponding decimal, to be saved in MySQL, that way I can order by it and do other comparisons to it.

But I need to be able to convert the decimal back to a fraction when showing to the user

so basically I need a function that will convert fraction string to decimal:

fraction_to_decimal("2 1/4");// return 2.25

and a function that can convert a decimal to a faction string:

decimal_to_fraction(.5); // return "1/2"

How can I do this?


Solution

  • I think I'd store the string representation too, as, once you run the math, you're not getting it back!

    And, here's a quick-n-dirty compute function, no guarantees:

    $input = '1 1/2';
    $fraction = array('whole' => 0);
    preg_match('/^((?P<whole>\d+)(?=\s))?(\s*)?(?P<numerator>\d+)\/(?P<denominator>\d+)$/', $input, $fraction);
    $result = $fraction['whole'] + $fraction['numerator']/$fraction['denominator'];
    print_r($result);die;
    

    Oh, for completeness, add a check to make sure $fraction['denominator'] != 0.