DEV Community

Avnish
Avnish

Posted on

Get the length of an Integer or a Float in Python

In Python, you can get the length of an integer or a float by converting them into strings and then finding the length of the string. Here are the examples:

Example 1: Get the Length of an Integer

def length_of_integer(num):
    return len(str(num))

# Example
number = 12345
length = length_of_integer(number)
print(f"Length of integer {number}: {length}")
Enter fullscreen mode Exit fullscreen mode

Output (Example 1):

Length of integer 12345: 5
Enter fullscreen mode Exit fullscreen mode

Example 2: Get the Length of a Float

def length_of_float(num):
    # Convert to string and remove the decimal point before finding length
    return len(str(num).replace('.', ''))

# Example
number = 123.456
length = length_of_float(number)
print(f"Length of float {number}: {length}")
Enter fullscreen mode Exit fullscreen mode

Output (Example 2):

Length of float 123.456: 6
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Function Definition: Both examples define a function (length_of_integer and length_of_float) that takes a number as input.

  2. Convert to String: The number is converted to a string using str() so that its length can be calculated.

  3. Handle Decimal Point: For float numbers, in order to get the actual length of digits excluding the decimal point, the function replaces the decimal point with an empty string using replace('.', '').

  4. Get Length: The len() function is used to find the length of the resulting string.

  5. Function Call: Each example demonstrates calling the function with a number and prints the length of the number.

These examples illustrate how to get the length of an integer or a float in Python by converting them into strings and finding the length of the resulting string.

Top comments (0)