Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to round to 2 decimal places in Python

Getting Started with Rounding in Python

One of the many things you can do in Python, a high-level, interpreted programming language, is to round numbers. In this post, we're going to explore how to round numbers to 2 decimal places. So, let's dive right in!

Understanding the Concept of Rounding

In our everyday life, we consistently round numbers. When we check the time and it's 5:47, we often say it's 'quarter to six', rounding the minutes to the nearest quarter hour. In programming, rounding works on similar principles. We often need to round numbers to make them easier to read, understand, or to limit the amount of storage they take up in our programs.

The Built-in round() Function

Python provides us with a handy built-in function called round() that you can use to round numbers. Here's a simple example of how it works:

print(round(3.14159))

The output will be 3 because Python rounds to the nearest whole number by default. Neat, right? But what if we wanted to keep some of the decimal places?

Rounding to Two Decimal Places

To round a number to 2 decimal places in Python, you provide a second argument to the round() function, indicating the number of decimal places you want to round to. Let's see how it works:

print(round(3.14159, 2))

The output will be 3.14. See how Python kept two decimal places?

How Python Handles Rounding

It's important to understand that Python uses "round half to even" rounding, also known as "bankers' rounding". This might be slightly different than what you learned in school, but it's a standard in many programming languages and scientific computations. Here's an example:

print(round(2.5))
print(round(3.5))

The output for both lines will be 2 and 4 respectively, not 3 and 4. Python rounds to the nearest even number when it's exactly halfway between two numbers.

Rounding with Precision

What if you want to round a number to the nearest hundredth? You can specify that by using an additional parameter in the round() function. For instance:

print(round(123.456, -2))

The output will be 100.0. Here, Python rounded 123.456 down to the nearest hundred (100.0), because 23.456 is closer to 00 than to 100.

Conclusion: Rounding is a Piece of Cake

Just like a skilled baker effortlessly slicing a cake into equal pieces, Python's round() function makes it easy to precisely cut down numbers to a specified level of detail. From rounding to the nearest whole number to specifying the exact decimal place, Python provides you with the flexibility and precision you need in your programming journey. So, the next time you're faced with a number that's just too long to handle, remember: Python's round() function is your trusty knife, always ready to help you slice through the complexity and get to the simplicity on the other side. Happy coding!