The most efficient and easy way to get the length of an integer is the “string conversion” approach.
The len() function returns the length of a string, not an integer, so we have to convert an input integer into a string using the str() function and then find its length using the len() function.
integer = 329484 print(len(str(integer))) # Output: 6
And we got the exact total number of digits, which is 3.
Negative integer
If we have a negative integer, we can use the abs() function before using the str() function to get the absolute value, convert it into a string, and then use the len() function to determine its length.
def get_length_str(n: int) -> int: return len(str(abs(n))) if n != 0 else 1 integer = -329484 print(get_length_str(integer)) # Output: 6
Floating-Point Numbers
For floating-point numbers, determining the “length” (number of digits) is more nuanced because of the decimal point and potential fractional parts.
Convert the float to a string using the str() function and split it into integer and fractional parts.
def get_length_float(n: float) -> tuple[int, int]: integer_part, fractional_part = str(abs(n)).split('.') return len(integer_part), len(fractional_part) number = 329.4845 print(get_length_float(number)) # Output: (3, 4)
You can see that the integer part has a length of 3, and the fractional part has a length of 4.
Here are two other ways:
- Using math.log10()
- Using Iterative Division
Approach 1: Using math.log10()
Another less-known approach is logarithm base 10. The main formula is: floor(log10(n)) + 1, which only works for positive integers.
For zero, log10 is undefined, and for numbers less than 1 (but integers can’t be negative here except zero).
So handling edge cases like n=0 is necessary. Wait, log10(0) would be a math error, so we need to handle n=0 separately.
import math def get_length_log(n: int) -> int: if n == 0: return 1 return math.floor(math.log10(abs(n))) + 1 integer = 329484 print(get_length_log(integer)) # Output: 6
Approach 2: Using Iterative Division
You can repeatedly divide the number by 10 until it becomes 0, counting iterations. That way, you will have an exact counting of digits.
def get_length_loop(n: int) -> int: if n == 0: return 1 n = abs(n) count = 0 while n > 0: n //= 10 count += 1 return count integer = 329484 print(get_length_loop(integer)) # Output: 6
It is a very less efficient approach since it can take long iterations if the input is too big.