Decimal to fraction

I made a little decimal-to-fraction converter and a fraction simplifier (along the way) if anyone wants to use it: (sorry, I could only make this in JavaScript, I don’t think Python allows you to change these things)

const Fraction = (function () {
    const sf = (top, bottom) => {
        if (bottom === 0) return top;
        return sf(bottom, top % bottom);
    };
    class Fraction {
        constructor (top, bottom) {
            if (top && !bottom) {
                let m = Math.pow(10, String(Math.decimal(top, true)).length);
                this.top = top * m;
                this.bottom = m;
                this.simplify(true);
                return;
            }
            this.top = top;
            this.bottom = bottom;
        }
        
        simplify (s) {
            let div = sf(this.top, this.bottom);
            if (s === true) {
                this.top /= div;
                this.bottom /= div;
                return;
            }
            return new Fraction(this.top / div, this.bottom / div);
        }
        
        toDecimal () {
            return this.top / this.bottom;
        }
    }
    Math._round = Math.round;
    Math.round = (n, t) => {
        if (!t) return Math._round(n);
        return Math._round(n / t) * t;
    };
    Math.decimal = (n, c) => {
        let str = String(n).split('.')[1];
        return Number(((!c) ? '0.' : '') + str);
    };
    return Fraction;
})();

usage:

new Fraction(0.6); // if you want to convert 0.6 to a fraction
new Fraction(5, 10); // if you want to just create a fraction object
fraction.simplify(); // only works if fraction is defined as a `Fraction` object

IMPORTANT: when working with classes you must use new

2 Likes

Woops, I forgot to add something, added now :grimacing: