How to Round Numbers in Python

Updated onbyAlan Morel
How to Round Numbers in Python

Part of why Python is so popular is how easy it is to work with numbers.

One of the most common operations you'll do with numbers is rounding them.

In this post, we'll learn the easiest ways to round numbers in Python.

Round to the nearest integer

The easiest way to round a float to the nearest integer is to use the built-in round() function.

Simply pass in your number and it will return the nearest integer.

number = 3.14159

rounded = round(number)

print(rounded)
3

Because 3.14159 is closer to 3 than 4, round() returns 3.

Round to a specific number of decimal places

Sometimes you want to round a number to a specific number of decimal places.

To round to a specific number of decimal places, you can use the round() function and pass in a second argument.

This second argument is the number of decimal places you want to round to.

Let's say you wanted to round to 2 decimal places.

number = 3.14159

rounded = round(number, 2)

print(rounded)
3.14

How to round up the nearest integer

When you want to round up to the nearest integer, you can use the math.ceil() function.

This function will take a float and return the smallest integer that is greater than or equal to the float.

Keep in mind that you'll need to import the math module to use this function.

import math

number = 3.14159

rounded = math.ceil(number)

print(rounded)
4

As expected, even though 3.14159 is closer to 3 than 4, math.ceil() returns 4 because it's the smallest integer that is greater than or equal to 3.14159.

How to round down the nearest integer

When you want to round down to the nearest integer, you can use the math.floor() function.

Unlike the math.ceil() function, this function will take a float and return the largest integer that is less than or equal to the float.

import math

number = 3.14159

rounded = math.floor(number)

print(rounded)
3

No surprises here. math.floor() returns 3 because it's the largest integer that is less than or equal to 3.14159.

Conclusion

In this post, we learned how to round numbers in Python.

We learned how to round to the nearest integer, round to a specific number of decimal places, round up to the nearest integer, and round down to the nearest integer.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.