# Return to Revisions

1 of 2

## Ruby, 127 bytes

f=->n{b=q=r=(m=n.sub(?.,'').to_r)/d=10**(p=n.count('0-9')-1)
b=r if(r=(q*d-=1).round.to_r/d).round(p).to_f.to_s==n while d>1
b}


Defines a function f which returns the result as a Rational. E.g. if you append this code

p f["1.7"]
p f["0."]
p f["0.001"]
p f["3.1416"]


You get

(5/3)
(0/1)
(1/667)
(355/113)


The loop is over denominators. I'm starting with the full fraction, e.g. 31416/10000 for the last example. Then I'm decrementing the denominator, proportionally decrement the numerator (and round it). If the resulting rational rounds to the same as the input number, I'm remembering a new best fraction.

 answered Sep 23 '14 at 13:04 Martin Ender 184k6161 gold badges409409 silver badges906906 bronze badges