In Python, the round() function is a built-in function used to round a number to a specified number of decimal places or to the nearest integer. The round() function takes two arguments: the number to be rounded and the number of decimal places to which it should be rounded.
The basic syntax for the round() function is as follows:
|
round(number, ndigits)
|
where number is the number to be rounded and ndigits is the number of decimal places to which it should be rounded. If ndigits is not provided, the default value is 0, which means that the number will be rounded to the nearest integer.
Here are some examples of using the round() function:
Example 1: Rounding to the nearest integer
|
x = 4.6
y = 4.4
print(round(x))
print(round(y))
|
Output:
5
4
In this example, the round() function is called on two decimal numbers 4.6 and 4.4. The round() function rounds 4.6 up to 5 and 4.4 down to 4.
Example 2: Rounding to a specified number of decimal places
|
x = 3.14159265
print(round(x, 2))
|
Output:
3.14
In this example, the round() function is called on a decimal number 3.14159265. The second argument 2 specifies that the number should be rounded to two decimal places, resulting in 3.14.
Example 3: Rounding negative numbers
|
x = -4.5
y = -4.4
print(round(x))
print(round(y))
|
Output:
-4
-4
In this example, the round() function is called on two decimal numbers 4.5 and 5.5. The round() function rounds 4.5 down to 4 and 5.5 up to 6. This behavior is due to the fact that in Python, ties are always rounded to the nearest even number, a convention known as "bankers' rounding".
In conclusion, the round() function is a useful tool in Python for rounding decimal numbers to a specified number of decimal places or to the nearest integer. The round() function can be called on any decimal number in Python, and its second argument specifies the number of decimal places to which the number should be rounded.