Python Reference ยท Built-in Functions
Python round() function
Reference for Python round(): round to a number of digits, why round(2.5) is 2, negative ndigits, float surprises and using decimal for exact rounding.
The built-in round() function rounds a number to a given number of decimal digits. With one argument it rounds to the nearest integer and returns an int; with ndigits it keeps the type of the input (a float stays a float).
Python rounds halves to the nearest even number, often called banker's rounding: round(0.5) is 0, round(1.5) is 2 and round(2.5) is 2. This reduces systematic bias when many values are rounded, but it surprises people who expect "round half up".
round(3.7) # 4 round(3.14159, 2) # 3.14 round(1234, -2) # 1200
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
round(number) round(number, ndigits)
| Name | Description |
|---|---|
number |
An int, float, Fraction, Decimal or any object defining __round__(). |
ndigits |
Optional number of digits after the decimal point. Negative values round to tens, hundreds, ... None behaves like omitting it. |
Return value: an int if ndigits is omitted or None; otherwise a number of the same type as number.
Raises: TypeError for non-numbers; OverflowError for infinity; ValueError for NaN when converting to an int.
Usage notes
- Halves go to the even neighbor.
round(0.5)is 0,round(2.5)is 2,round(3.5)is 4. If you need school-style rounding, usedecimalwithROUND_HALF_UP. - Floats are approximations.
2.675is stored as slightly less than 2.675, soround(2.675, 2)gives2.67. This is not a bug inround; the stored number really is below the half. - Money: do not round binary floats. Use
decimal.Decimalwithquantize(), or store integer cents. round(x)returns anint,round(x, 0)returns a float such as3.0. That is a classic source of surprises in output.- Negative
ndigitsrounds to the left of the decimal point:round(1234, -2)is1200. round()rounds the value; formatting only changes the display.f"{x:.2f}"produces a string and leavesxalone. Format specs also use round-half-even on the exact stored value.- Other directions:
math.floor(down),math.ceil(up),math.trunc(toward zero) andint()(truncation). - Custom types can support
round()by implementing__round__(self, ndigits=None).
Related
abs(),divmod(),int(),float(),format()- Lessons: Numbers, Math and random, String formatting