TITLE: Finding the leading digit(s) in any number
QUESTION [5 upvotes]: I am somewhat perplexed by this (presumably very simple) issue.
Simply, I am trying to find the leading digit(s) in any number (related question). Here is some nice python code (from this question):
import math

def first_n_digits(num, n):
    # where n is the number of leading digits of interest
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

This works great for most numbers, for example:
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456

The problem is this does not work for num=1000 and n=1.
first_n_digits(1000, 1)
10

This issue does not appear when num = 10,100,10000,100000. Just num = 1000.
How can one deal with this edge case? I have not found any others so far. I expect there to be some very simple solution which I have overlooked.

REPLY [2 votes]: Python documentation for math.log says

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

So it is possible that $\text{math.log}(1000,10)$ is returning a value very slightly less than 3 due to rounding errors, and when you apply int to this you get $2$. Try evaluating $\text{int}(\text{math.log}(1000,10))$ to see whether this evaluates to $2$ or $3$. (I see Mees de Vries has already done this test).
There is an alternative function in the math module called math.log10:

Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).