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

Fractions
f := FloatToFraction(a);
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}`
}
import static java.lang.Integer.parseInt;
import static java.lang.Math.pow;
import static java.lang.String.valueOf;
String s = valueOf(a), f;
s = s.substring(s.indexOf('.') + 1);
int n = parseInt(s);
if (n == 0) f = valueOf((int) a);
else {
    record GCF() {
        static int of(int a, int b) {
            return b == 0 ? a : of(b, a % b);
        }
    }
    int d = (int) pow(10, s.length()),
        gcf = GCF.of(n, d), i = (int) a;
    if (gcf != 0) {
        n = n / gcf;
        d = d / gcf;
    }
    f = n + "/" + d;
    if (i != 0) f = i + " " + f;
}
s = str(a)
if (i := s.find('.')) == -1:
    f = str(a)
else:
    n = int(s := s[i + 1:])
    def gcf(a, b):
        return gcf(b, a % b) if b else a
    d = 10 ** len(s)
    v = gcf(n, d)
    i = int(a)
    if v:
        n = int(n / v)
        d = int(d / v)
    if i: f = f'{i} {n}/{d}'
    else: f = f'{n}/{d}'
from fractions import Fraction
f = Fraction(a)

New implementation...
< >
reilas