From: Glenn Jackman Date: 2009-07-23T23:40:04+09:00 Subject: Re: Bug Rounding Floats? (9.245 * 100).round => 924? S/B 925! At 2009-07-22 03:22PM, "ddoherty03" wrote: > On Jul 22, 1:13�pm, Glenn Jackman wrote: > > A workaround, convert the expression to a string and back to a number: > > � � num = Float("%.1f" % (9.245 * 100)).round > > � � puts "yippee" if num == 925 > > Glenn, > > Thanks for the explanation. If I could pick your brain for a second > on how to generalize your workaround, I would greatly appreciate it. > > Here is how I tried to implement the "nround" method. > > ###################################### > class Float > def nround(n = 0) > (self * 10.0 ** n).round / 10.0 ** n > end > end > ###################################### > > My issue is getting the workaround to deal with the parameter n > properly. Taking Bil Kleb's advice, require 'bigdecimal' require 'bigdecimal/util' class Float def nround(n=0) (self.to_d * (10.0**n).to_d).round.to_f / 10.0**n end end p 9.245.nround(2) # => 9.25 -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous