Count the decimal places of a Float in Python

Borislav Hadzhiev

Last updated: Apr 10, 2024

Reading timeยท4 min

- 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()

**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.

main.py

`my_float = 3.14567 # โ Count decimal places in a float count_after_decimal = str(my_float)[::-1].find('.') print(count_after_decimal) # ๐๏ธ 5`

The code for this article is available on GitHub

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.main.py

`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.

main.py

`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.

main.py

`my_float = 3.14567834 - 1.3123 print(my_float) # ๐๏ธ 1.8333783399999999 count_after_decimal = str(my_float)[::-1].find('.') print(count_after_decimal) # ๐๏ธ 16`

You can use the `exponent`

attribute to get the number of digits after the
decimal point if you use the `Decimal`

class.

main.py

`from decimal import Decimal my_decimal = Decimal('3.14567') count_after_decimal = abs(my_decimal.as_tuple().exponent) print(count_after_decimal) # ๐๏ธ 5`

The code for this article is available on GitHub

The as_tuple() method returns a named tuple representation of the number.

main.py

`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.

main.py

`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.

main.py

`print(abs(-50)) # ๐๏ธ 50 print(abs(50)) # ๐๏ธ 50`

You can also use the `split()`

method to count the decimal places of a
floating-point number.

main.py

`my_float = 3.14567 count_after_decimal = len(str(my_float).split('.')[1]) print(count_after_decimal) # ๐๏ธ 5`

The code for this article is available on GitHub

We used the str() class to convert the float to a string and split the string on the period.

main.py

`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.

You can also use the `re.sub()`

method to count the decimal places in a float.

main.py

`import re my_float = 3.14567 count_after_decimal = len(re.sub(r'^\d+\.', '', str(my_float))) print(count_after_decimal) # ๐๏ธ 5`

The code for this article is available on GitHub

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 `[0-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.

You can learn more about the related topics by checking out the following tutorials:

- Add zeros to a Float after the Decimal in Python
- Remove the Decimal part from a Float in Python
- How to Remove the trailing Zeros from a Decimal in Python
- Round a Float to 1, 2 or 3 Decimal places in Python
- Split a Float into Integer and Decimal parts in Python
- Format number with comma as thousands separator in Python
- SyntaxError: invalid decimal literal in Python [Solved]
- SyntaxError: leading zeros in decimal integer literals are not permitted
- Pandas: Make new Column from string Slice of another Column