Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to round in Python

Introduction

Rounding numbers is a common task in mathematics and programming. It is the process of reducing a number to a simpler and more manageable form, usually by eliminating decimal places. In Python, there are several built-in functions and libraries available to help you perform rounding operations. In this blog post, we will explore different methods to round numbers in Python, discussing their pros and cons, and providing code examples to illustrate their usage.

Understanding Rounding

Before we dive into the various techniques for rounding numbers in Python, let's first understand the concept of rounding. Rounding means approximating a number to a specified degree of accuracy. In most cases, this involves reducing the number of decimal places to a more manageable form.

For example, consider the number 3.14159. If we want to round this number to two decimal places, we would end up with 3.14. Rounding can also involve rounding to the nearest whole number, as in rounding 3.6 to 4.

There are different methods of rounding, such as:

  1. Round half up: In this method, if the number following the rounding digit is 5 or more, we round up; otherwise, we round down. For example, 3.5 would round to 4, and 3.4 would round to 3.
  2. Round half down: In this method, if the number following the rounding digit is greater than 5, we round up; otherwise, we round down. For example, 3.5 would round to 3, and 3.6 would round to 4.
  3. Round half to even (Bankers' rounding): In this method, if the number following the rounding digit is exactly 5, we round to the nearest even number; otherwise, we follow the round half up method. For example, 3.5 would round to 4, 4.5 would round to 4, and 4.6 would round to 5.

Now that we have a basic understanding of rounding, let's explore how to implement these methods in Python.

Using the round() Function

Python has a built-in round() function that can be used to round numbers to a specified number of decimal places. The syntax for the round() function is as follows:

round(number, ndigits)

Here, number is the number you want to round, and ndigits is the number of decimal places you want to round to. If ndigits is not specified, it defaults to 0, which means rounding to the nearest whole number.

Examples

Let's see some examples of using the round() function in Python:

# Rounding to the nearest whole number
print(round(3.6))  # Output: 4
print(round(3.4))  # Output: 3

# Rounding to a specified number of decimal places
print(round(3.14159, 2))  # Output: 3.14
print(round(9.87654, 3))  # Output: 9.877

It's important to note that the round() function in Python uses "round half to even" method, also known as "Bankers' rounding". This means that when the number following the rounding digit is exactly 5, the function will round to the nearest even number. This can lead to some unexpected results if you're not aware of this behavior.

Limitations

While the round() function is simple to use and works well for most purposes, it has some limitations:

  1. It only supports the "round half to even" method, which may not be suitable for all applications.
  2. It can produce incorrect results for very large numbers or numbers with many decimal places due to floating-point representation limitations in Python.

Using the math Library

Python's math library provides additional functions for rounding numbers, including the floor() and ceil() functions, which round down and up, respectively. To use these functions, you'll first need to import the math library:

import math

The math.floor() Function

The math.floor() function rounds a number down to the nearest whole number, effectively "chopping off" any decimal places. The syntax for the math.floor() function is as follows:

math.floor(number)

Here, number is the number you want to round down.

Examples

Let's see some examples of using the math.floor() function in Python:

import math

print(math.floor(3.6))  # Output: 3
print(math.floor(3.4))  # Output: 3
print(math.floor(-3.6))  # Output: -4

The math.ceil() Function

The math.ceil() function rounds a number up to the nearest whole number. The syntax for the math.ceil() function is as follows:

math.ceil(number)

Here, number is the number you want to round up.

Examples

Let's see some examples of using the math.ceil() function in Python:

import math

print(math.ceil(3.6))  # Output: 4
print(math.ceil(3.4))  # Output: 4
print(math.ceil(-3.6))  # Output: -3

Custom Rounding Functions with math.floor() and math.ceil()

While the math.floor() and math.ceil() functions only round to the nearest whole number, you can use them to create custom rounding functions for rounding to a specified number of decimal places or implementing different rounding methods. For example, you can create a custom "round half up" function using the following code:

import math

def round_half_up(number, ndigits=0):
    multiplier = 10 ** ndigits
    return math.floor(number * multiplier + 0.5) / multiplier

print(round_half_up(3.14159, 2))  # Output: 3.14
print(round_half_up(3.5))  # Output: 4
print(round_half_up(3.6))  # Output: 4

In this example, we first multiply the input number by a power of 10 equal to the desired number of decimal places (using the 10 ** ndigits expression). Then, we add 0.5 and use the math.floor() function to round down to the nearest whole number. Finally, we divide the result by the same power of 10 to obtain the rounded number with the specified number of decimal places.

Using the decimal Library

For situations where you need more precise control over rounding or need to work with very large numbers or numbers with many decimal places, you can use Python's decimal library. The decimal library provides a Decimal class for working with decimal numbers and supports various rounding methods, including "round half up", "round half down", and "round half to even".

To use the decimal library, you'll first need to import it and create a Decimal object from your number:

from decimal import Decimal

number = Decimal('3.14159')

Rounding with the Decimal.quantize() Method

The Decimal class provides a quantize() method that can be used to round numbers to a specified number of decimal places and using a specified rounding method. The syntax for the quantize() method is as follows:

rounded_number = number.quantize(exp, rounding_method)

Here, number is the Decimal object you want to round, exp is a Decimal object representing the desired number of decimal places, and rounding_method is a constant from the decimal library specifying the rounding method to use.

Examples

Let's see some examples of using the quantize() method to round numbers with the decimal library:

from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN

number = Decimal('3.14159')
exp = Decimal('0.01')  # Two decimal places

# Round half up
rounded_half_up = number.quantize(exp, ROUND_HALF_UP)
print(rounded_half_up)  # Output: 3.14

# Round half down
rounded_half_down = number.quantize(exp, ROUND_HALF_DOWN)
print(rounded_half_down)  # Output: 3.14

# Round half to even (Bankers' rounding)
rounded_half_even = number.quantize(exp, ROUND_HALF_EVEN)
print(rounded_half_even)  # Output: 3.14

In these examples, we create a Decimal object for our number and a Decimal object representing the desired number of decimal places (in this case, two decimal places). We then use the quantize() method with different rounding methods to round the number as needed.

Conclusion

In this blog post, we've explored various methods for rounding numbers in Python, including the built-in round() function, the math library's floor() and ceil() functions, and the decimal library's quantize() method. Depending on your specific needs and the level of precision required, you can choose the appropriate method for your rounding tasks.

Remember that each method has its pros and cons, and it's essential to understand the underlying behavior of these functions to avoid unexpected results. With practice and a solid understanding of the concepts presented here, you'll be well-equipped to handle rounding tasks in your Python programs.