Logo

Programming-Idioms

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

Idiom #348 Convert a decimal value into a fraction

Parse a number, a, into a mathematical fraction, f.

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

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

let s = a.toString(), f, n, i
i = s.indexOf('.')
if (i == -1) i = s.length - 1
s = s.substring(++i)
n = parseInt(s)
if (!n) f = Math.trunc(a)
else {
    let gcf = (a, b) => !b ? a : gcf(b, a % b),
        d = Math.pow(10, s.length),
        v = gcf(n, d)
    i = Math.trunc(a)
    if (v) {
        n = n / v
        d = d / v
    }
    if (i) f = `${i} ${n}/${d}`
    else f = `${n}/${d}`
}

New implementation...
< >
reilas