From: Patrick Hurley Date: 2005-03-31T23:26:31+09:00 Subject: Re: Integer/Float oddity On Thu, 31 Mar 2005 23:09:46 +0900, horati0@linuxmail.org wrote: > not really an oddity, more a lack of understanding on my part regarding > ruby's internal type conversion... > > (100*(1.15-1)) > => 15.0 > > (100*(1.15-1)).to_int > => 14 > > (100*(1.15-1)).to_int.round > => 15 > > 15.0.to_int > => 15 > > what am i missing here? i never would have thought to use .round to > get the 'correct' result unless someone told me. by correct i mean if > i was doing this with a paper and pencil, i would expect to get 15, not > 14. > > any insight would be appreciated, especially a way (if possible) to > override this behaviour so i dont run into this in the future. > > thanks, > horati0 > > Two quick notes - I think you meant > (100*(1.15-1)).round.to_int > => 15 See if this clears anything up: printf("%.15f", (100*(1.15-1))) 14.999999999999991=> nil The result is not really 15, but just really really close, due to the imprecision of floats - always round moving to ints - to_i is a "floor" function. Similarly be very careful when comparing floats. Patrick