From: Mark Hubbart Date: 2005-05-06T02:10:16+09:00 Subject: Re: Float to Rational On 5/4/05, Luke Galea wrote: > Hi All, > > I need to convert a float to a fraction.. So 1.5 to 1 1/2.. > The rational class would represent at least 3/2 well.. but I was surprised to > find that there is no way to easily go from float to rational.. > > Am I missing an easier way? there is no built-in way (that I know of), but here are two methods I wrote a while back that should cover all the bases: ---- require 'mathn' class Float def to_r n = 1 n *= 2 until (self*n) % 1 == 0 (self*n).to_i/n end def round_to_r i, d = to_s.split /\./ i.to_i * 10**d.size + d.to_i / 10**d.size end end ---- #to_r directly converts the float to a rational, and includes any intrinsic inaccuracies. This will be *exactly* equal to the original float. 2.125.to_r ==>17/8 0.2.to_r ==>3602879701896397/18014398509481984 #round_to_r uses the displayed representation of the float to generate a value that, while not always being the actual value of the float, is much better for display, or if you know you want it rounded a tiny bit. 0.2.round_to_r ==>1/5 0.23.round_to_r ==>23/100 It could deal with being a little smarter, for catching repeating digits and the like. cheers, Mark