Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #349 Convert a fraction into a decimal value

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

Fractions
a := f.ToFloat;
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;
String s[] = f.split("[ /]");
int m = s.length,
    n = parseInt(s[m - 2]),
    d = parseInt(s[m - 1]);
double a = ((double) n / d);
if (m > 2) a = a + parseInt(s[0]);
import static java.math.MathContext.DECIMAL128;
import java.math.BigDecimal;
String s[] = f.split("[ /]");
int m = s.length;
BigDecimal n = new BigDecimal(s[m - 2]),
           d = new BigDecimal(s[m - 1]),
           a = n.divide(d, DECIMAL128);
if (m > 2) a = a.add(new BigDecimal(s[0]));
from re import split
s = split('[ /]', f)
*i, n, d = map(int, s)
a = sum(i, 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

New implementation...
< >
reilas