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,
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;
}