# How can I have $10$ to $99$ evaluate to $1$, $100$ to $999$ evaluate to $10$, and so on?

Sorry for the strange title, as I don't really know the proper terminology.

I need a formula that returns 1 if the supplied value is anything from 10 to 99, returns 10 if the value is anything from 100 to 999, returns 100 if the value is anything from 1000 to 9999, and so on.

I will be translating this to code and will ensure the value is never less than 1, in case that changes anything.

It's probably something really simple but I can't wrap my head around a nice way to do this so... thanks!

• Try logarithms (and rounding)! – Babelfish May 9 at 7:41
• Unless time is absolutely of the essence for this operation, the best way to do it is to convert the number to a string and then take its length. This is robust and legible. Note that the mathematical functions below may suffer from floating point errors. – Mees de Vries May 9 at 12:59
• @MeesdeVries: It's not only robust and legible; it is way shorter and probably way faster (using floating-point operations here is slow and stupid)! – user21820 May 11 at 14:32

I think your function is $$f(x) = 10^{\left \lfloor \log_{10}(x) \right \rfloor - 1}$$ where $$\lfloor r \rfloor$$ denotes the largest integer less than or equal to $$r$$.

Is a mathematical formula really needed ? Or a function (in the sense of a programming language) that does this job ok? As you say you are going to translate this into code it is simpler to directly translate your description to code, without having to find a mathematical formula

Here is it in Python: (you may have to handle numbers less than 10 differently)

def mylog(x):

#assumes x is a positive integer between 10 and 10^25

tenpowers = [10**k for k in range(25)]

for k in range(25):

if x-1 < tenpowers[k]:

return  tenpowers[k-1]


$$f(x) = 10^{[\log_{10} x]-1}$$ where $$[x]$$ denotes floor