How to Round number in Python

In Python, numbers can be rounded using the built-in round() function and other methods, depending on the desired precision and rounding behavior. Here’s a detailed explanation:

1. Using the round() Function

The round() function rounds a number to the nearest integer or to a specified number of decimal places.

Syntax:

round(number, ndigits)
  • number: the number to be rounded.
  • ndigits : An optional parameter, an integer number of decimal places to round to. If not specified, rounds to the nearest integer.

Examples:

# Rounding to the nearest integer
print(round(4.6))  # Output: 5
print(round(4.4))  # Output: 4

# Rounding to a specific number of decimal places
print(round(3.14159, 2))  # Output: 3.14
print(round(2.71828, 3))  # Output: 2.718

# Rounding negative numbers
print(round(-2.5))  # Output: -2
print(round(-3.5))  # Output: -4

2. The math.floor() and math.ceil() Functions

If you want to always round down or up, use the math.floor() or math.ceil() functions of the math module.

  • math.floor(): Rounds down to the nearest integer.
  • math.ceil(): Rounds up to the nearest integer.

Examples:

import math

# Rounding down
print(math.floor(4.8))  # Output: 4
print(math.floor(-4.8)) # Output: -5

# Rounding up
print(math.ceil(4.2))   # Output: 5
print(math.ceil(-4.2))  # Output: -4

3. Rounding Toward Zero with int()

If you need to truncate the decimal part without rounding, converting to an integer will remove the decimal portion.

Examples:

print(int(4.8))   # Output: 4
print(int(-4.8))  # Output: -4

4. Using decimal.Decimal for Custom Rounding

For precise rounding in financial or scientific applications, you can use the decimal module. It offers control over rounding modes.

Example:

from decimal import Decimal, ROUND_HALF_UP, ROUND_DOWN

# ROUND_HALF_UP (traditional rounding)
num = Decimal('2.675')
print(num.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))  # Output: 2.68

# ROUND_DOWN (always rounds down)
num = Decimal('2.678')
print(num.quantize(Decimal('0.01'), rounding=ROUND_DOWN))    # Output: 2.67

5. Rounding in NumPy

If you’re working with arrays, the numpy library provides rounding functions like numpy.round().

Example:

import numpy as np

arr = np.array([1.234, 2.456, 3.678])
print(np.round(arr, 2))  # Output: [1.23 2.46 3.68]

Rounding Behavior

  1. Ties (e.g., 2.5, 3.5): Python’s round() rounds to the nearest even number to reduce bias in large datasets (Banker’s Rounding).
print(round(2.5))  # Output: 2
print(round(3.5))  # Output: 4

2. Control over Rounding Modes: Use decimal for strict control over rounding behavior.

Choosing the Appropriate Function

  • For general purpose rounding use round().
  • For rounding in one direction use math.floor() or math.ceil().
  • For very precise or controlled rounding use decimal.Decimal.
  • Use numpy for array rounding.