Python built-in Method - round()

The round() function is a built-in Python method that is used to round a floating-point number to a specified number of decimal places. The round() function can also be used to round a floating-point number to the nearest integer.

The syntax for the round() function is as follows:

round(number, ndigits=None)
Source:ww‮‬w.theitroad.com
  • number: The floating-point number to be rounded.
  • ndigits: The number of decimal places to round to. If ndigits is not provided, the round() function will round the number to the nearest integer.

Here are some examples of how the round() function can be used:

>>> x = 3.14159
>>> round(x, 2)
3.14

In this example, we use the round() function to round the x floating-point number to 2 decimal places. The result is a new floating-point number with only 2 decimal places.

>>> y = 5.6
>>> round(y)
6

In this example, we use the round() function to round the y floating-point number to the nearest integer. The result is an integer value.

>>> z = 7.4999
>>> round(z)
7
>>> round(z, 1)
7.5

In this example, we use the round() function to round the z floating-point number to the nearest integer and to 1 decimal place. When rounding to the nearest integer, the round() function uses the round-to-even tie-breaking rule. In this case, the number is rounded down to 7. When rounding to 1 decimal place, the number is rounded up to 7.5.

The round() function is a useful built-in method in Python that provides a convenient way to round floating-point numbers to a specified number of decimal places or to the nearest integer. It is often used in financial applications and scientific calculations where precision is important.