Table of Contents
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.
PYTHONnumber = 3.14159
rounded = round(number)
print(rounded)
BASH3
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.
PYTHONnumber = 3.14159
rounded = round(number, 2)
print(rounded)
BASH3.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.
PYTHONimport math
number = 3.14159
rounded = math.ceil(number)
print(rounded)
BASH4
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.
PYTHONimport math
number = 3.14159
rounded = math.floor(number)
print(rounded)
BASH3
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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js