Python round() With Examples

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

Python round()

Python round() function syntax is:

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

Output:

round() to even side

Output:

round() with ndigit as None

Output:

round() with negative ndigit

Output:

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:

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

Output:

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.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: