Snippet to turn decimals to fractions

A little something I've been tinkering with.

This snippet will turn a decimal number into a proper fraction.

I'm no mathematician, so if you have a more elegant solution, definitely let me know.

I've enjoyed wrestling with this one :grin:

P.S. I've set it up to ignore anything past the third decimal, because at that point the fraction would be so small I don't think it would be worth considering.

Number to convert to fraction:
{formtext: name=number; default=1.625}{if: isnumber(number) == "yes"}
{if: number <> floor(number)}
{note: preview=no}
{int=split(number, ".")[1] if split(number, ".")[1] <> "" else 0}{decimals=split(number, ".")[2]}{=int}.{=decimals}
{numerator=extractregex(decimals, "\d{0,3}")}{=numerator}
{denominator=10^len(numerator)}
{factors1=filter([numerator/i for i in seq(1, numerator)], item -> testregex(item, "\.") == "no")}{=factors1}
{factors2=filter([denominator/i for i in seq(1, denominator)], item -> testregex(item, "\.") == "no")}{=factors2}
{gcf=filter(factors1, item -> includes(factors2, item) == "yes")[1]}
{endnote: trim=right}
{if: int > 0}{=catch(int, "")} {endif}{=numerator/gcf}/{=denominator/gcf}
{else}
{=abs(number)}
{endif}
{else}
{error: Please input a number}
{endif}

3 Likes