Notes

`round()` Function in Python [ English ]

< Prev Next >

1. Introduction

The round() function in Python is a built-in function used to round a number to a specified number of digits. It returns the number rounded to the nearest integer or to a specified number of decimal places.

The round() function is commonly used in programs where approximate values or formatted numbers are required, such as financial calculations, measurements, and statistical results.

2. Syntax

round(number, ndigits)

Parameters

  1. number The numeric value that needs to be rounded.

  2. ndigits (optional) The number of decimal places to which the number should be rounded.

    • If not specified, the number is rounded to the nearest integer.

3. Return Value

4. Example: Rounding to Nearest Integer

print(round(4.6))
print(round(4.2))

Output

5
4

Explanation

5. Example with Decimal Places

print(round(3.14159, 2))

Output

3.14

Explanation

6. Example with One Decimal Place

print(round(7.856, 1))

Output

7.9

Explanation

7. Example with Negative ndigits

Negative values for ndigits round numbers to tens, hundreds, etc.

print(round(125, -1))
print(round(125, -2))

Output

120
100

Explanation

8. Example Showing Special Rounding Behavior

print(round(2.5))
print(round(3.5))

Output

2
4

Explanation

Python uses "round half to even" (also called banker's rounding):

9. Practical Example

price = 123.4567

rounded_price = round(price, 2)

print("Rounded Price:", rounded_price)

Output

Rounded Price: 123.46

Explanation

10. Summary

< Prev Next >