September 11, 2024

How to Round Numbers in Python

Rounding numbers in Python can be easily done using built-in functions. Depending on your needs, you can round a number to a specific number of decimal places, or round it to the nearest integer. Below are some common methods to round numbers in Python.

1. Using the round() Function

The round() function rounds a number to a specified number of decimal places. If no decimal places are specified, it rounds the number to the nearest integer.

Example 1: Rounding to the Nearest Integer

# Rounding to the nearest integer
number = 4.6
rounded_number = round(number)
print(rounded_number)

Output:

5

In this example, the number 4.6 is rounded to the nearest integer, which is 5.

Example 2: Rounding to Specific Decimal Places

# Rounding to two decimal places
number = 4.6789
rounded_number = round(number, 2)
print(rounded_number)

Output:

4.68

In this example, the number 4.6789 is rounded to two decimal places, resulting in 4.68.

2. Using the math.floor() and math.ceil() Functions

The math.floor() function rounds a number down to the nearest integer, while the math.ceil() function rounds a number up to the nearest integer.

Example 1: Rounding Down with math.floor()

import math

number = 4.7
rounded_down = math.floor(number)
print(rounded_down)

Output:

4

In this example, the number 4.7 is rounded down to 4.

Example 2: Rounding Up with math.ceil()

import math

number = 4.3
rounded_up = math.ceil(number)
print(rounded_up)

Output:

5

In this example, the number 4.3 is rounded up to 5.

3. Using the int() Function

The int() function truncates the decimal part of a number, effectively rounding it down to the nearest integer.

Example:

# Truncating the decimal part using int()
number = 4.9
truncated_number = int(number)
print(truncated_number)

Output:

4

In this example, the number 4.9 is truncated to 4.

4. Rounding Numbers in a List

You can round numbers in a list using list comprehension combined with the round() function.

Example:

# Rounding numbers in a list
numbers = [4.567, 3.4567, 8.1234, 9.8765]
rounded_numbers = [round(num, 2) for num in numbers]
print(rounded_numbers)

Output:

[4.57, 3.46, 8.12, 9.88]

In this example, each number in the list is rounded to two decimal places.