Logo

Programming-Idioms

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
New implementation

Type ahead, or select one

Explain stuff

To emphasize a name: _x → x

Please be fair if you are using someone's work

You agree to publish under the CC-BY-SA License

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 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}`
}