Convert mixed fraction string for swimming in PHP

I suggested that in PHP there will be an easy way to convert a string of type 18 5/16to float 18.3125. I cannot find a direct function for this. Is there one, or do I need to write my own?

+3
source share
1 answer

I do not think such a function exists - at least not related to PHP.

Writing a function to perform this operation, if your string always has the same format, should not be too complicated; for example, I would say something like this should do the trick:

$str = '18 5/16';
var_dump(calc($str));

function calc($str) {
    $int = 0;
    $float = 0;
    $parts = explode(' ', $str);
    if (count($parts) >= 1) {
        $int = $parts[0];
    }
    if (count($parts) >= 2) {
        $float_str = $parts[1];
        list($top, $bottom) = explode('/', $float_str);
        $float = $top / $bottom;
    }
    return $int + $float;
}

What you will get the following output:

float 18.3125


And you can get something shorter with a few regexes; something like this should do the trick, I suppose:

function calc($str) {
    if (preg_match('#(\d+)\s+(\d+)/(\d+)#', $str, $m)) {
        return $m[1] + $m[2] / $m[3];
    }
    return 0;
}



Else, PHP, , , : Eval Math.

: , , .

+4

All Articles