Public Group

# number of diggits in a integer

This topic is 4311 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How do I find the number of digits in a integer?? like: 1 = 1 10 = 2 100 = 3 I tried with i.size() but that didnt work.. :/

##### Share on other sites
What language are you using?

c++

##### Share on other sites
for(int i = 0; x > 9; x /= 10, i++);

Would that work?

##### Share on other sites
Quote:
 Original post by Nice Coderfor(int i = 0; x > 9; x /= 10, i++);Would that work?

i will be off by one and not accesible outside the scope of the for loop.

but either way the important thing, Nanook, is that you be able to explain to your teacher why it works...

If it's a homework assignment then try thinking about it for a while. It wouldn't have been assigned if you didn't have the tools to solve it.

-me

##### Share on other sites
Depends on how the number is represented. Decimal,hex,bin,octal or others system could produce different numbers of digits.

Lets take the number 123d in decimal:

-123d in decimal(123) and has 3 digits,
-123d in hex(7Bh) has 2 digits,
-123d in binary(1111011b) has 7 digits
-123d in octal(173o) has 3 digits.

##### Share on other sites
Quote:
 Original post by Palidinei will be off by one and not accesible outside the scope of the for loop.

Not to mention that it's horribly inefficient to use a loop to do something for which a simple formula exists.

##### Share on other sites
The best way to do this is to convert the number to a string and find the length of the string.

(just kidding)

##### Share on other sites
Quote:
 Original post by deathkrushThe best way to do this is to convert the number to a string and find the length of the string. (just kidding)

hum.. why not?

##### Share on other sites
Quote:
 Original post by deathkrushThe best way to do this is to convert the number to a string and find the length of the string. (just kidding)

:)
Ever read The Daily WTF? It's amazing how often the "convert to string" approach is taken in real-world applications by programmers who should know better.

1. 1
Rutin
26
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 10
• 10
• 9
• 9
• 10
• ### Forum Statistics

• Total Topics
631751
• Total Posts
3002087
×

## Important Information

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!