Python How to Round Numbers

E-mc2 written on chalkboard

To round a number in Python, use the built-in round() function.

For example:

x = round(2.33453)
print(x)

Output:

2

To specify how many decimals you want to round, give a second argument to the round() function.

For example, let’s round a decimal to two decimal places:

x = round(2.33453, 2)
print(x)

Output:

2.33

How to Round a Number Up

To round a number up to the nearest integer, use the math module’s ceil() function.

For example:

import math

x = math.ceil(2.4213)
print(x)

Output:

3

How to Round a Number Down

To round a number down to the nearest integer, use the math module’s floor() function.

For example:

import math

x = math.floor(2.4213)
print(x)

Output:

2

Conclusion

To round numbers in Python, use the round() function.

To round up to the nearest integer, use math.ceil(). To round down to the nearest integer, use math.floor().

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *