Converting a percents or fractions to decimal from a variable

Anyone know an easy way to take a percent/fraction variable and convert it to a decimal number? I won’t know which it will be.


$Fraction = '3/16';
$Percent = '25%';


$Convert = ?; // .125


There is no “fraction” datatype.

But it’s only simple division in both cases

fraction -> float would be numerator divided by denominator

and per cent (per 100) -> float would be number divided by 100

Are your variables strings?

Yeah they are strings. I guess the only way would be to match to see if it’s a percent or fraction, then process it?

Ideally it would be better to have more control over the input so you know what they are and don’t need extra processing. Different form inputs?

Otherwise you need to figure out what is what from the possible sting formats.

If the “fraction” will always have “/” and the “per cent” will always have “%” then I guess that would be easy enough.

You can split() the fraction string on the “/”, cast to numeric and divide $piece[0] by $piece[1]

You could replace() the “%” with nothing to get rid of it, cast to numeric and divide by 100

As PHP is a dynamically typed language, you “usually” won’t need to cast the string to an int as PHP will do that for you.