- Count Decimal Places in Python
- Using the decimal library to count decimal places in Python
- Using the len() and split() function to count decimal places in Python
- Further reading:
- Using the find() function to count decimal places in Python
- Number of decimal places python
- # Table of Contents
- # Count the decimal places of a Float in Python
- # Count the decimal places of a Decimal object in Python
- # Count the decimal places of a Float using split()
- # Count the decimal places of a Float using re.sub()
- # Additional Resources
Count Decimal Places in Python
In Python, we can represent decimal values using the float datatype. The decimal point divides the integer from the fractional part. The maximum value a float object can have is 1.8 x 10^308.
In this article, we will discuss how to count the decimal places in Python. We will take a float value and return the total number of digits after the decimal point.
Using the decimal library to count decimal places in Python
The decimal library allows us to work with float values. We can convert these values to objects of the Decimal class from this library. There are many methods associated with this class that can perform various functions on these values.
The as_tuple() function is used to return the information about the floating value in a tuple. It returns the sign of the number (positive or negative), the digits in the number, and the exponent value.
The exponent attribute can be used to return the exponent value from this tuple. This exponent value is the same as the number of digits in the decimal place with a negative sign. We can use the abs() function to get the absolute value of this attribute, removing the negative sign.
In the above example, we use the decimal.Decimal() constructor to create an object of the Decimal class. We get the exponent value of this object using the as_tuple() function. Its absolute value is displayed using the abs() function.
Using the len() and split() function to count decimal places in Python
The len() and split() function work with string objects. The former is used to return the length of the given string and the latter can split a given string into a list of substrings based on some character.
We can use these functions together to count decimal places in Python.
First, we will convert the float value to a string using the str() function. Then we will split the list based on the . character to return two substrings. The second substring contains the decimal part and its length can be calculated using the len() function.
Further reading:
How to Format Float to 2 Decimal Places in Python
Print Percentage Sign in Python
Using the find() function to count decimal places in Python
The find() function is used to return the index of the first occurrence of an element in a string. We can use it with string slicing to count decimal places in Python.
We can slice string using the square brackets ( [] ). In these brackets, we can specify the start, end, and step values for the string slicing. We can specify the step as -1 to reverse the string. We can convert a float value to a string using the str() function and reverse it using this method.
After reversing the string, the decimal part comes in front. We can find the occurrence of the decimal point using the find() function. The index of the decimal point will be the same as the total decimal places.
This logic is implemented in the code below.
Number of decimal places python
Last updated: Feb 21, 2023
Reading time · 4 min
# Table of Contents
# Count the decimal places of a Float in Python
To get the number of digits after the decimal point:
- Use the str() class to convert the number to a string.
- Use string slicing to reverse the string.
- Use the str.find() method to find the index of the period.
Copied!my_float = 3.14567 # ✅ Count decimal places in a float count_after_decimal = str(my_float)[::-1].find('.') print(count_after_decimal) # 👉️ 5
The example counts the number of digits after the decimal in a floating-point number.
We used the str() class to convert the float to a string and reversed the string using string slicing.
Copied!my_float = 3.14567 print(str(my_float)[::-1]) # 👉️ 76541.3
The syntax for string slicing is my_str[start:stop:step] .
We specified a value for the step of -1 to reverse the string.
The last step is to use the str.find() method to get the index of the period.
Copied!my_float = 3.14567 count_after_decimal = str(my_float)[::-1].find('.') print(count_after_decimal) # 👉️ 5
Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .
Since indexes are zero-based, the index of the period is equal to the number of decimal places in the number.
Note that you might run into unexpected rounding issues when using floating-point numbers.
Copied!my_float = 3.14567834 - 1.3123 print(my_float) # 👉️ 1.8333783399999999 count_after_decimal = str(my_float)[::-1].find('.') print(count_after_decimal) # 👉️ 16
# Count the decimal places of a Decimal object in Python
You can use the exponent attribute to get the number of digits after the decimal point if you use the Decimal class.
Copied!from decimal import Decimal my_decimal = Decimal('3.14567') count_after_decimal = abs(my_decimal.as_tuple().exponent) print(count_after_decimal) # 👉️ 5
The as_tuple method returns a named tuple representation of the number.
Copied!my_decimal = Decimal('3.14567') print(my_decimal.as_tuple()) print(my_decimal.as_tuple().sign) # 👉️ 0 print(my_decimal.as_tuple().digits) # 👉️ (3, 1, 4, 5, 6, 7) print(my_decimal.as_tuple().exponent) # 👉️ -5
The named tuple has sign , digits and exponent attributes.
To get the number of digits after the decimal, we have to change the sign of the exponent value, so we passed the result to the abs() function.
Copied!from decimal import Decimal my_decimal = Decimal('3.14567') count_after_decimal = abs(my_decimal.as_tuple().exponent) print(count_after_decimal) # 👉️ 5
The abs function returns the absolute value of a number. In other words, if the number is positive, the number is returned, and if the number is negative, the negation of the number is returned.
Copied!print(abs(-50)) # 👉️ 50 print(abs(50)) # 👉️ 50
# Count the decimal places of a Float using split()
You can also use the split() method to count the decimal places of a floating-point number.
Copied!my_float = 3.14567 count_after_decimal = len(str(my_float).split('.')[1]) print(count_after_decimal) # 👉️ 5
We used the str() class to convert the float to a string and split the string on the period.
Copied!my_float = 3.14567 print(str(my_float).split('.')) # 👉️ ['3', '14567']
The second element in the list is the decimal part.
Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(a_list) — 1 .
We accessed the list at index 1 and used the len() function to get the count of the decimal places.
The len() function returns the length (the number of items) of an object.
# Count the decimal places of a Float using re.sub()
You can also use the re.sub() method to count the decimal places in a float.
Copied!import re my_float = 3.14567 count_after_decimal = len(re.sub(r'^\d+\.', '', str(my_float))) print(count_after_decimal) # 👉️ 5
The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.
The first argument we passed to the method is a regular expression.
The \d character matches the digits 9 (and many other digit characters).
The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the digit).
We used a backslash to escape the period because periods have a special meaning in regular expressions.
In its entirety, the regular expression matches one or more digits at the start of the string followed by a period and removes the characters by replacing them with an empty string.
The last step is to use the len() function to count the number of digits after the decimal.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.