Python round(): Round a Number to the Nearest Integer or Decimal Place

The round() function rounds a number to a specified number of decimal places. It’s useful for financial calculations, data formatting, and improving numerical readability.

Example

print(round(3.14159, 2))

Output:

3.14

Rounds 3.14159 to 2 decimal places.

Syntax

round(number, ndigits=None)
  • number → The number to round.
  • ndigits (optional) → Number of decimal places to keep (default: 0).
  • Returns → A rounded integer or floating-point number.

1. Rounding to the Nearest Integer

print(round(4.6))  # Output: 5
print(round(4.3))  # Output: 4

If ndigits is not specified, it rounds to the nearest integer.

2. Rounding to a Specific Decimal Place

print(round(3.14159, 3))  # Output: 3.142
print(round(9.8765, 1))   # Output: 9.9

Keeps a specific number of decimal places.

3. Rounding Negative Numbers

print(round(-2.8))   # Output: -3
print(round(-2.4))   # Output: -2

Negative numbers round away from zero or towards zero, depending on .5 rules.

4. Rounding to the Nearest Multiple of 10

print(round(1234, -2))  # Output: 1200

Useful for rounding large numbers.

5. Handling .5 Rounding Behavior (Bankers’ Rounding)

Python follows “bankers’ rounding” (ties round to the nearest even number).

print(round(2.5))  # Output: 2
print(round(3.5))  # Output: 4
  • 2.5 rounds to 2 (even).
  • 3.5 rounds to 4 (even).

6. Using round() in Division Calculations

average = round(10 / 3, 2)
print(average)  # Output: 3.33

Keeps precision in floating-point division.

Key Notes

  • Rounds numbers to the nearest integer or decimal place.
  • Uses “bankers’ rounding” (ties round to the nearest even number).
  • Useful for formatting financial data and scientific calculations.
  • Handles both positive and negative numbers.

By using round(), you can format numbers neatly, ensure accuracy in calculations, and control decimal precision efficiently. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top