0

Count amount of digits in a given number or input by the user.

Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62

3 Answers3

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
4

Convert the number to a string and count the characters.

Karlth
  • 3,267
  • 2
  • 27
  • 28
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