Python: Check a decimal with a precision of 2
48. Check Decimal Precision
Write a Python program to check a decimal with a precision of 2.
Sample Solution:
Python Code:
def is_decimal(num):
import re
dnumre = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
result = dnumre.search(num)
return bool(result)
print(is_decimal('123.11'))
print(is_decimal('123.1'))
print(is_decimal('123'))
print(is_decimal('0.21'))
print(is_decimal('123.1214'))
print(is_decimal('3.124587'))
print(is_decimal('e666.86'))
Sample Output:
True True True True False False False
Pictorial Presentation:
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to validate that a decimal number in a string has exactly two digits after the decimal point.
- Write a Python script to check if input numbers conform to a precision of 2 decimal places.
- Write a Python program to search a text for decimals and then filter those that have more than two digits after the decimal point.
- Write a Python program to use regex to verify that a decimal string is formatted with a precision of 2, and print True if it is.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to split a string with multiple delimiters.
Next: Write a Python program to remove words from a string of length between 1 and a given number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.