Logo

Programming-Idioms

Parse a value, f, into a decimal number, a.

For example, `1/2` is 0.5, and `3 1/8` is 3.125.

https://en.wikipedia.org/wiki/Fraction
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
let z = 0, n, d, i, a
if ((i = f.indexOf(' ')) != -1) {
    z = parseInt(f.substring(0, i))
    f = f.substring(++i).trim()
}
i = f.indexOf('/')
n = parseInt(f.substring(0, i))
d = parseInt(f.substring(++i))
a = z + (n / d)
import static java.lang.Integer.parseInt;
int z = 0, n, d, i;
double a;
if ((i = f.indexOf(' ')) != -1) {
    z = parseInt(f.substring(0, i));
    f = f.substring(++i).trim();
}
i = f.indexOf('/');
n = parseInt(f.substring(0, i));
d = parseInt(f.substring(++i));
a = z + ((double) n / d);
Fractions
a := f.ToFloat;
z = 0
if (i := f.find(' ')) != -1:
    z = int(f[:i])
    f = f[i + 1:].lstrip()
n, d = map(int, f.split('/'))
a = z + (n / d)
from fractions import Fraction
a = map(Fraction, f.split())
a = sum(map(float, a))
a = f.split.map(&:to_r).sum.to_f