Rounding numbers in Python is an essential task, especially when dealing with data precision. Python’s built-in round()
function uses the rounding half to even strategy, which rounds numbers like 2.5
to 2
and 3.5
to 4
. This method helps minimize rounding bias in datasets. To round numbers to specific decimal places, you can use the round()
function with a second argument specifying the number of decimals.
For more advanced rounding strategies, you can explore Python’s decimal
module or use NumPy and pandas for data science applications. NumPy arrays and pandas DataFrames offer methods for rounding numbers efficiently. In NumPy, you can use functions like np.round()
, np.ceil()
, np.floor()
, and np.trunc()
to apply different rounding strategies. For pandas, the df.round()
method allows rounding of entire DataFrames or specific columns.
By the end of this tutorial, you’ll understand that:
- Python uses the rounding half to even strategy, where ties round to the nearest even number.
- Python’s default rounding strategy minimizes rounding bias in large datasets.
- You can round numbers to specific decimal places using Python’s
round()
function with a second argument. - Different rounding strategies can be applied using Python’s
decimal
module or custom functions for precision control. - NumPy and pandas provide methods for rounding numbers in arrays and DataFrames, offering flexibility in data manipulation.
You won’t get a treatise on numeric precision in computing, although you’ll touch briefly on the subject. Only a familiarity with the fundamentals of Python is necessary, and the math should feel familiar if you’ve had high school algebra.
You’ll start by looking at Python’s built-in rounding mechanism.
Take the Quiz: Test your knowledge with our interactive “Rounding Numbers in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:
Get Your Code:Click here to download the free sample code you’ll use to learn about rounding numbers in Python.
Python’s Built-in round()
Function
Python has a built-in round()
function that takes two numeric arguments, n
and ndigits
, and returns the numbern
rounded to ndigits
. The ndigits
argument defaults to zero, so leaving it out results in a number rounded to an integer. As you’ll see, round()
may not work quite as you expect.
The way most people are taught to round a number goes something like this:
Round the number
n
top
decimal places by first shifting the decimal point inn
byp
places. To do that, multiplyn
by 10ᵖ (10 raised to thep
power) to get a new number,m
.Then look at the digit
d
in the first decimal place ofm
. Ifd
is less than 5, roundm
down to the nearest integer. Otherwise, roundm
up.Finally, shift the decimal point back
p
places by dividingm
by 10ᵖ.
It’s an algorithm! For example, the number 2.5
rounded to the nearest whole number is 3
. The number 1.64
rounded to one decimal place is 1.6
.
Now open up an interpreter session and round 2.5
to the nearest whole number using Python’s built-in round()
function:
>>> round(2.5)2
Gasp!
Check out how round()
handles the number 1.5
:
>>> round(1.5)2
So, round()
rounds 1.5
up to 2
, and 2.5
down to 2
!
Before you go raising an issue on the Python bug tracker, rest assured you that round(2.5)
is supposed to return 2
. There’s a good reason why round()
behaves the way it does.
In this tutorial, you’ll learn that there are more ways to round a number than you might expect, each with unique advantages and disadvantages. round()
behaves according to a particular rounding strategy—which may or may not be the one you need for a given situation.
You might be wondering, Can the way I round numbers really have that much of an impact? Next up, take a look at just how extreme the effects of rounding can be.
How Much Impact Can Rounding Have?
Suppose you have an incredibly lucky day and find $100 on the ground. Rather than spending all your money at once, you decide to play it smart and invest your money by buying some shares of different stocks.
The value of a stock depends on supply and demand. The more people there are who want to buy a stock, the more value that stock has, and vice versa. In high-volume stock markets, the value of a particular stock can fluctuate on a second-by-second basis.
Read the full article at https://realpython.com/python-rounding/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]