How to Round Numbers in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To round a number in Python, you can use the built-in round() function. The round() function rounds a floating-point number to the nearest integer, or to a specified number of digits after the decimal point. Here are some examples:

To round a number to the nearest integer:

x = 3.14159
rounded = round(x)
print(rounded)  # Output: 3

To round a number to a specified number of decimal places:

x = 3.14159
rounded = round(x, 2)
print(rounded)  # Output: 3.14

In this example, the second argument of round() specifies the number of decimal places to round to.

Note that the default rounding mode used by the round() function is “round half to even,” also known as “banker’s rounding.” This means that if the number to be rounded ends in .5, it will be rounded to the closest even integer. If you want to use a different rounding mode, such as always rounding up or always rounding down, you can use the decimal module or the math module to achieve that.

Tags:

related content