Count amount of digits in a given number or input by the user.
Asked
Active
Viewed 868 times
0
-
1Please be more specific about what you mean. If you ask a vague question people are unlikely to answer it. – templatetypedef Jan 07 '11 at 10:20
-
1http://stackoverflow.com/questions/554521/how-can-i-count-the-digits-in-an-integer-without-a-string-cast – Lukáš Lalinský Jan 07 '11 at 10:22
-
3Hint (assuming this is homework) - divide the number by ten until you hit zero. – Amarghosh Jan 07 '11 at 10:35
3 Answers
8
Independent of programming language:
floor(log10(x))+1
where x is your number (>0).
If you want to handle 0 and negative numbers, I'd suggest something like this:
x == 0 ? 1 : floor(log10(abs(x)))+1

Jakob
- 24,154
- 8
- 46
- 57
-
If `x==0` guard with an `if`, it's probably the best way to handle this, and put abs(x) inside the log to handle negatives, for which `log10` is undefined. – Jan 07 '11 at 10:24
-
@cHao: That's a tricky question. How many digits are there in the float `float x = 1.0/3`? Not very useful either. If the OP is actually asking about non-integers, I'd surrender to the obvious: treating the user input as a string and checking its length (minus characters that we don't care about). – Jakob Jan 07 '11 at 10:33
-
As for usefulness...yeah, it'd be kinda rare. However, there'd be uses, mostly when doing formatted text output and such. – cHao Jan 07 '11 at 10:40
0
I assume you want to know how many base 10 digits do you need to represent a binary number (such as an int).
double x = something(positive);
double base = 10.0;
double digits = ceil(log(x + 1.0) / log(base));

diego
- 1