Python Practice › If-Else Programs › Program 39
Round a float to 2 decimals
Write a Python program that checks whether a value is a float and, if so, rounds it to 2 decimal places.
Input
25.3614, 40
Output
25.3614 -> 25.36 40 is not a float
Approach
- Check the type with
isinstance, then useround(x, 2).
Solution
for value in [25.3614, 40]: if isinstance(value, float): print(value, "->", round(value, 2)) else: print(value, "is not a float")Output
25.3614 -> 25.36 40 is not a float
Line by line
Line 3
round(value, 2) keeps two digits after the decimal point.
Learn the concept
New to this topic? Read the lesson, then come back.