Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to construct a function thats output is equal to the number of digits used to represent the number given as an input.

For example:
$f(5) = 1$
$f(9) = 1$
$f(13) = 2$
$f(99) = 2$
$f(682) = 3$
$f(999) = 3$
$f(9999)= 4$

Is it even possible with one function and if not, why not?
Can anyone help me with this or at least point me in the right direction?

share|cite|improve this question
possible duplicate of Checking the digits in an integer – Isaac May 6 '11 at 4:02
You have essentially defined the function, before you asked whether it is possible to define it. $$f(n)=\lfloor \log_{10}|n|\rfloor+1,$$ given in Listing's answer, is a nice formula for it, but $$f(n)=\text{ the number of digits used to represent }n$$ is a fine definition of a function $f$. – Jonas Meyer Aug 10 '11 at 7:16
up vote 12 down vote accepted

The function is for integers in $\mathbb{Z}$

$D_{10}(n)=\lfloor \log_{10}|n| \rfloor+1$

if $n \neq 0$ and $D_{10}(0):=1$. You can leave the absolute function away if you just want to look at positive integers.

Note that for any base you want you could use

$D_{b}(n)=\lfloor \log_{b}|n| \rfloor+1$

for digits in base b, this is quite nice.

You have to use floor because especially $D_{10}(10)=2$. $\log_{10}n$ is the logarithm to base 10.

share|cite|improve this answer
Yours is better, not to say correct. :-) – Asaf Karagila May 5 '11 at 8:30
Thanks yes, it is a mistake I also make often :) – Listing May 5 '11 at 8:31
Thanks, that is a wonderful solution. One question though, what does ":=" mean? – logicbird May 5 '11 at 8:46
@logicbird: ":=" means 'is defined to be'. In particular, since $\log_{10} 0$ is undefined, you must address that specific input separately. – Brandon Carter May 5 '11 at 8:49
@Brandon: oh, I see. I figured 0 would need to be handled separately but I was not familiar with that syntax. thanks. – logicbird May 5 '11 at 8:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.