Python round usage detailed explanation and examples
Python round Usage Detailed Explanation and Examples
round is a built-in function in Python that rounds a floating-point number to a specified number of decimal places. Its syntax is as follows:
round(number, ndigits)
number: The number to be rounded.ndigits: The number of decimal places to be rounded, which can be a positive or negative integer.
Next, I’ll give three examples to illustrate the use of the round function.
Example 1: Rounding a Floating-Point Number to a Specified Number of Decimal Places
x = 3.14159
rounded_num = round(x, 2)
print(rounded_num) # Output: 3.14
In the above example, we round the floating-point number x to two decimal places, resulting in 3.14.
Example 2: Rounding a Floating-Point Number to an Integer
y = 3.8
rounded_num = round(y)
print(rounded_num) # Output: 4
In this example, we round the floating-point number y to the nearest integer. Since 3.8 is closer to 4, the result is 4.
Example 3: Rounding a Floating-Point Number to a Negative Number of Decimal Places
z = 1234.5678
rounded_num = round(z, -2)
print(rounded_num) # Output: 1200.0
In this example, we round the floating-point number z to a negative number of decimal places. -2 rounds the number to the hundreds place (the digit to the left of the tens place), resulting in 1200.0.
Through these three examples, we can see the flexibility of the round function, which can be used for different rounding needs. Note that round returns a floating-point number, not an integer.