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}")
Output (Example 1):
Length of integer 12345: 5
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}")
Output (Example 2):
Length of float 123.456: 6
Explanation:
Function Definition: Both examples define a function (
length_of_integer
andlength_of_float
) that takes a number as input.Convert to String: The number is converted to a string using
str()
so that its length can be calculated.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('.', '')
.Get Length: The
len()
function is used to find the length of the resulting string.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)