Logo

Programming-Idioms

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

For example, 1.23 is `1 23/100`.

https://en.wikipedia.org/wiki/Decimal
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
#include <cmath>
#include <iostream>
#include <numeric>
#include <regex>
using namespace std;
string s {to_string(a)}, f;
regex p {"\\."};
sregex_token_iterator r {
    begin(s), end(s), p, -1
};
int i {stoi(*r)}, n {stoi(*++r)},
    d {int(pow(10, r->length()))},
    v {gcd(n, d)};
if (v) {
    n /= v;
    d /= v;
}
if (not n) f = to_string(i);
else {
    f = to_string(n) + '/' + to_string(d);
    if (i) f = to_string(i) + ' ' + f;
}
let s = a.toString(), f,
    [x, y] = s.split('.'),
    i = parseInt(x), n = parseInt(y),
    d = Math.pow(10, y.length),
    gcf = (a, b) => !b ? a : gcf(b, a % b),
    v = gcf(n, d)
if (v) {
    n /= v;
    d /= v;
}
if (!n) f = i.toString()
else {
    f = `${n}/${d}`
    if (i) f = `${i} ${f}`
}
import static java.lang.Integer.parseInt;
import static java.lang.Math.pow;
import static java.lang.String.valueOf;
String s[] = valueOf(a).split("\\."), f;
int i = parseInt(s[0]), n = parseInt(s[1]),
    d = (int) pow(10, s[1].length()), v;
record GCF() {
    static int of(int a, int b) {
        return b == 0 ? a : of(b, a % b);
    }
}
if ((v = GCF.of(n, d)) != 0) {
    n = n / v;
    d = d / v;
}
if (n == 0) f = valueOf(i);
else if (i != 0) f = "%s %s/%s".formatted(i, n, d);
else f = "%s/%s".formatted(n, d);
Fractions
f := FloatToFraction(a);
from math import gcd
i, n = str(a).split('.')
d = 10 ** len(n)
i, n = map(int, (i, n))
factor = gcd(n, d) or 1
n //= factor
d //= factor
if not n:
    s = str(i)
elif not i:
    s = f'{n}/{d}'
else:
    s = f'{i} {n}/{d}'
from fractions import Fraction
f = Fraction(a)
from fractions import Fraction
def mixed_number(value) -> str:
    value = Fraction(str(value))
    signed = value < 0
    integer = 0
    n, d = value.as_integer_ratio()
    if signed:
        n = -n
    if n and (n > d):
        integer, n = divmod(n, d)
    if n == d:
        integer = n
        n = 0
    if not integer and n:
        s = f'{n}/{d}'
    elif not n:
        s = str(integer)
    else:
        s = f'{integer} {n}/{d}'
    if signed:
        s = f'-({s})'
    return s
F: str = mixed_number(A)