Round a float to 2 decimals

EasyIf-Else Programs · 39 of 64

Write a Python program that checks whether a value is a float and, if so, rounds it to 2 decimal places.

Advertisement
Input
25.3614, 40
Output
25.3614 -> 25.36
40 is not a float

Approach

  1. Check the type with isinstance, then use round(x, 2).

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs