Python round() function is used to perform rounding operation on numbers.

## Python round()

Python round() function syntax is:

1 2 3 |
round(number[, ndigits]) |

The **number** is rounded to **ndigits** precision after the decimal point.

If ndigit is not provided or is None, then nearest integer is returned.

While rounding the input number to an integer, if both round up and round down values are equally close then even number is returned. For example, 10.5 will be rounded to 10 whereas 11.5 will be rounded to 12.

Any integer value is valid for ndigits (positive, zero, or negative).

## Python round() function examples

Let’s look at some example of round() function.

**round() to integer**

1 2 3 4 5 6 |
print(round(10, 2)) print(round(10.2)) print(round(10.8)) print(round(11.5)) |

Output:

1 2 3 4 5 6 |
10 10 11 12 |

**round() to even side**

1 2 3 4 5 |
# if both side of rounding is same, even is returned print(round(10.5)) print(round(12.5)) |

Output:

1 2 3 4 |
10 12 |

**round() with ndigit as None**

1 2 3 4 5 |
print(round(1.5)) # OR print(round(1.5, None)) |

Output:

1 2 3 4 |
2 2 |

**round() with negative ndigit**

1 2 3 4 5 |
print(round(100, 0)) print(round(100.1234, -4)) print(round(100.1234, -5)) |

Output:

1 2 3 4 5 |
100 100.0 0.0 |

## Python round float

When rounding is applied on floating point numbers, the result can be sometimes surprising. It’s because the numbers are stored in binary format and mostly decimal fractions cannot be represented exactly as binary fractions.

Python does the approximation and presents us the rounded value, because of this floating point arithmetic can sometimes result in surprising values.

For example:

1 2 3 4 5 6 7 8 |
>>>.1 + .1 == .2 True >>>.1 + .1 + .1 == .3 False >>>.1 + .1 + .1 + .1 == .4 True |

Let’s see some examples of round() function with floats.

1 2 3 4 5 |
print(round(2.675, 2)) print(round(1.2356, 2)) print(round(-1.2356, 2)) |

Output:

1 2 3 4 5 |
2.67 1.24 -1.24 |

Notice that first float rounding seems wrong. Ideally, it should be rounded to 2.68.

This is the limitation of arithmetic operations with floats, we shouldn’t rely on conditional logic when dealing with floating point numbers.

## round() with custom object

We can use round() function with a custom object too if they implement __round__() function. Let’s look at an example.

1 2 3 4 5 6 7 8 9 10 11 |
class Data: id = 0 def __init__(self, i): self.id = i def __round__(self, n): return round(self.id, n) d = Data(10.5234) print(round(d, 2)) print(round(d, 1)) |

Output:

1 2 3 4 |
10.52 10.5 |

Reference: Official Documentation