0

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

3
  • 1
    Please be more specific about what you mean. If you ask a vague question people are unlikely to answer it. Commented Jan 7, 2011 at 10:20
  • 1
    stackoverflow.com/questions/554521/… Commented Jan 7, 2011 at 10:22
  • 3
    Hint (assuming this is homework) - divide the number by ten until you hit zero. Commented Jan 7, 2011 at 10:35

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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).
As for usefulness...yeah, it'd be kinda rare. However, there'd be uses, mostly when doing formatted text output and such.
4

Convert the number to a string and count the characters.

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.