# Ways to find number of digits an Integer has?

Page 1 of 1

## 4 Replies - 13679 Views - Last Post: 08 November 2011 - 10:35 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=254891&amp;s=6cfc65af29b8b3ca2196b6f0859c885d&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 jace427

Reputation: 2
• 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

• I wrote you an code

Reputation: 983
• Posts: 3,451
• 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.

### #3 jace427

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

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

Posted 08 November 2011 - 08:06 PM

xclite, 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.

### #4 Skaggles

• THE PEN IS MIGHTIER

Reputation: 251
• 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

```

### #5 jace427

Reputation: 2
• 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!