Count amount of digits in a given number or input by the user.
-
1Please be more specific about what you mean. If you ask a vague question people are unlikely to answer it.templatetypedef– templatetypedef2011-01-07 10:20:50 +00:00Commented Jan 7, 2011 at 10:20
-
1stackoverflow.com/questions/554521/…Lukáš Lalinský– Lukáš Lalinský2011-01-07 10:22:21 +00:00Commented Jan 7, 2011 at 10:22
-
3Hint (assuming this is homework) - divide the number by ten until you hit zero.Amarghosh– Amarghosh2011-01-07 10:35:49 +00:00Commented Jan 7, 2011 at 10:35
Add a comment
|
3 Answers
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
3 Comments
Jakob
@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).cHao
As for usefulness...yeah, it'd be kinda rare. However, there'd be uses, mostly when doing formatted text output and such.