PHP convert decimal into fraction and back?

前端 未结 14 975
面向向阳花
面向向阳花 2020-12-05 07:43

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,

14条回答
  •  我在风中等你
    2020-12-05 08:24

    Just adding a bit more logic to Derek's accepted answer - check for "division by zero" and whole number input check.

    function fractionToDec($input) {
        if (strpos($input, '/') === FALSE) {
            $result = $input;
        } else {
            $fraction = array('whole' => 0);
            preg_match('/^((?P\d+)(?=\s))?(\s*)?(?P\d+)\/(?P\d+)$/', $input, $fraction);
            $result = $fraction['whole'];
    
            if ($fraction['denominator'] > 0)
                $result += $fraction['numerator'] / $fraction['denominator'];
        }
    
        return $result;
    }
    

提交回复
热议问题