Stefano Crocco
4/10/2009 3:14:00 PM
Alle Friday 10 April 2009, Aldric Giacomoni ha scritto:
> How does one use .finite? effectively? I tried with (1.0/3).finite? =>
> true... I tried with BigDecimal.. Still true. I'm pretty sure these numbers
> aren't finite. How do I make this work?
According to the ri documentation, Float#finite? only returns false if self is
not inifinite and self.nan? is false. For example,
(1/0.0).finite?
=> false
What you wanted to know is whether the number has a finite or infinite number
of decimal digits. Unfortunately, I don't think such a method exists. You
can't do that with floats, because all floats have a finite number of decimal
digits (you can't very well store infinite digits in your computer's memory,
after all). I suppose it can be done with the Rational class, but you'd have
to write the method yourself. Here's a simple example of how this could be
done:
require 'rational'
class Rational
def finite_digits?
d = denominator
return false if d % 2 !=0 and d % 5 != 0
d = d / 2 while d % 2 ==0
d = d / 5 while d % 5 == 0
d == 1
end
end
Stefano