With modern destructuring syntax, the best/safest answer can be simplified to:
const parseFraction = fraction => {
const [numerator, denominator] = fraction.split('/').map(Number);
return numerator / denominator;
}
// example
parseFraction('3/2'); // 1.5
In other words, split the faction by its /
symbol, turn both resulting strings into numbers, then return the first number divided by the second ...
... all with only two (very readable) lines of code.
EDIT
The above assumes that for 1.5
you will only get 3/2
... and not 1 1/2
. But, as @Aro Parada noted in a comment, you might need to handle such whole numbers.
If so, you could use a very similar split
-based approach, but with a reverse
to handle the fact that we only sometimes have a whole number:
const parseFraction = fractionString => {
const [fraction, wholeNumber = 0] = fractionString.trim().split(' ').reverse();
const [numerator, denominator] = fraction.split('/').map(Number);
return Number(wholeNumber) + numerator / denominator;
}
You might not even need the trim
in there; strings like 1 1/2
will work even without it, but if you can have 1 1/2
you'll want to keep the trim
.
eval(fraction)
would of course work, but only if you trust your input. – Dicho0.0065 + 0.0005 = 0.006999999999999999;
– Bergstein