class Integer def digits d = 1 i = self.abs while i > 10 do i /= 10 d += 1 end return d end end
Ways to find number of digits an Integer has?
Page 1 of 14 Replies - 2267 Views - Last Post: 08 November 2011 - 10:35 PM
#1
Ways to find number of digits an Integer has?
Posted 08 November 2011 - 06:31 PM
The other day I had to come up with a method for determining the number of digits an Integer had, in Ruby. This is one way, but as a lover of all things math, I'm sure there are many, many others. So, out of nothing but pure curiousity, I was wondering what the collective creative minds of Ruby enthusiasts would come up with if I asked for other ways to solve this problem. This is just for fun, it is not about better/worse, just different. I look forward to your replies.
Replies To: Ways to find number of digits an Integer has?
#2
Re: Ways to find number of digits an Integer has?
Posted 08 November 2011 - 07:39 PM
class Integer
def digits
i.to_s.size
end
end
Another method to consider is using log10 of a number.
#3
Re: Ways to find number of digits an Integer has?
Posted 08 November 2011 - 08:06 PM
#4
Re: Ways to find number of digits an Integer has?
Posted 08 November 2011 - 10:31 PM
I was interested and figured I'd work something out for float numbers.
class Float
def digits
self.to_s.gsub(/\./, '').size
end
def digits_left
self.to_s.split('.')[0].size
end
def digits_right
self.to_s.split('.')[1].size
end
end
#5
Re: Ways to find number of digits an Integer has?
Posted 08 November 2011 - 10:35 PM
Also nice. Forgot to mention with xclite's post, but probably want to stuff abs in after self to account for negative numbers in order to ignore the minus sign, but still very nice. Thanks!
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote









|