4 Replies - 6266 Views - Last Post: 08 November 2011 - 10:35 PM Rate Topic: -----

#1 jace427  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 31-October 11

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. :)

class Integer
	def digits
		d = 1
		i = self.abs
		while i > 10 do
			i /= 10
			d += 1
		end
		return d
	end
end



Is This A Good Question/Topic? 0
  • +

Replies To: Ways to find number of digits an Integer has?

#2 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 902
  • View blog
  • Posts: 3,163
  • Joined: 12-May 09

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.
Was This Post Helpful? 1
  • +
  • -

#3 jace427  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 31-October 11

Re: Ways to find number of digits an Integer has?

Posted 08 November 2011 - 08:06 PM

View Postxclite, on 08 November 2011 - 07:39 PM, said:

class Integer
    def digits
       i.to_s.size
    end
end



Another method to consider is using log10 of a number.


Very cool! Didn't think of that. Thanks.
Was This Post Helpful? 0
  • +
  • -

#4 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 251
  • View blog
  • Posts: 640
  • Joined: 01-March 09

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


Was This Post Helpful? 0
  • +
  • -

#5 jace427  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 31-October 11

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!
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1