In many situations, you will find yourself in a situation where you want to round a floating-point number to the nearest integer in your Python 3 code. In this article, I will explain how.
1. Using the Round() Function
You can use the Round built-in function in Python to round a number to the nearest integer.
>>> round(2.4) 2 >>> round(2.6) 3 >>> round(2.5) 2
Note that in Python 3, the return type is int. However, if you are still on Python 2, the return type will be a float so you would need to cast the returned value into int.
Another thing to notice here is that according to Python’s documentation, any floating number that is mid-way between two integers (e.g. 2.5, 3.4. etc…) will be rounded to the nearest even choice. For example:
>>> round(2.5) 2 >>> round(3.5) 4
2. Without Using any Built-in Functions
If you want to round a number to the nearest integer without using any built-in functions in Python (maybe for a coding interview or something), then you can define the following function.
def round_number(x): if (x - int(x)) < 0.5: return int(x) else: return int(x) + 1
There you go! Happy Python coding 🙂
Check out the Courses section!
- The Python Learning Path (From Beginner to Mastery)
- Learn Computer Science (From Zero to Hero)
- Coding Interview Preparation Guide
- The Programmer’s Guide to Stock Market Investing
- How to Start Your Programming Blog?
Are you Beginning your Programming Career?
I provide my best content for beginners in the newsletter.
- Python tips for beginners, intermediate, and advanced levels.
- CS Career tips and advice.
- Special discounts on my premium courses when they launch.
And so much more…