How to round to the nearest tenth in python
To round number to nearest 10, use round() function. We can divide the value by 10, round the result to zero precision, and multiply with 10 again. Or you can pass a negative value for precision. The negative denotes that rounding happens to the left of the decimal point. In this tutorial, we will write Python programs to round a number to its nearest 10 or 100. For example, if the number is 3652, then its nearest number to
10 is 3650. And the nearest 100 is 3700. Example 1 – Round Number to Nearest 10 using round()In this example, we will read a number from user, and round the value to its nearest 10 using round() function. Python Program number = int(input('Enter a number :')) rounded = round(number/10)*10 print('Rounded Number :', rounded) Output Enter a number :3652 Rounded Number : 3650 Or you can also provide a negative number as the second argument for round() function, to round to those number of digits before decimal point. Python Program number = int(input('Enter a number :')) rounded = round(number, -1) print('Rounded Number :', rounded) Output Enter a number :3652 Rounded Number : 3650 Example 2 – Round Number to Nearest 100 using round()In this example, we will round the number to its nearest 100 using round() function. Python Program number = int(input('Enter a number :')) rounded = round(number/100)*100 print('Rounded Number :', rounded) Output Enter a number :3652 Rounded Number : 3700 Or you can also provide a negative number as the second argument for round() function, to round to those number of digits before decimal point. To round to nearest 100, we need to provide -2 as second argument to round(). Python Program number = int(input('Enter a number :')) rounded = round(number, -2) print('Rounded Number :', rounded) Output Enter a number :3652 Rounded Number : 3700 ConclusionConcluding this Python Tutorial, we learned how to use round() function to round a number to nearest 10 or 100. You can use the same process to find the nearest number to any digit before the decimal point. There are two things here:
Its important to distinguish between both:
The To print it with a decimal component, you need to format how its displayed, not change how its stored and used, this doesn't make a difference what the type of the number is. Here you can see I am printing an integer with a decimal component, even though it doesn't have one:
And if you have a number with a decimal component; then depending on how you display it, various things will happen:
So make sure you are doing the right thing at the right place. It’s the era of big data, and every day more and more business are trying to leverage their data to make informed decisions. Many businesses are turning to Python’s powerful data science ecosystem to analyze their data, as evidenced by Python’s rising popularity in the data science realm. One thing every data science practitioner must keep in mind is how a dataset may be biased. Drawing conclusions from biased data can lead to costly mistakes. There are many ways bias can creep into a dataset. If you’ve studied some statistics, you’re probably familiar with terms like reporting bias, selection bias and sampling bias. There is another type of bias that plays an important role when you are dealing with numeric data: rounding bias. In this article, you will learn:
This article is not a treatise on numeric precision in computing, although we will touch briefly on the subject. Only a familiarity with the fundamentals of Python is necessary, and the math involved here should feel comfortable to anyone familiar with the equivalent of high school algebra. Let’s start by looking at Python’s built-in rounding mechanism. Python’s Built-in round() FunctionPython has a built-in The way most people are taught to round a number goes something like this:
It’s a straightforward algorithm! For example, the number Now open up an interpreter session and round Gasp! How does So, Before you go raising an issue on the Python bug tracker, let me assure you that In this article, you’ll learn that there
are more ways to round a number than you might expect, each with unique advantages and disadvantages. You might be wondering, “Can the way I round numbers really have that much of an impact?” Let’s 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. Let’s run a little experiment. We’ll pretend the overall value of the stocks you purchased fluctuates by some small random number each second, say between $0.05 and -$0.05. This fluctuation may not necessarily be a nice value with only two decimal places. For example, the overall value may increase by $0.031286 one second and decrease the next second by $0.028476. You don’t want to keep track of your value to the fifth or sixth decimal place, so you decide to chop everything off after the third decimal place. In rounding jargon, this is called truncating the number to the third decimal place. There’s some error to be expected here, but by keeping three decimal places, this error couldn’t be substantial. Right? To run our experiment using Python, let’s start by writing a >>>
The Next, let’s define the initial parameters of the simulation. You’ll need two variables: one to keep track of the actual value of your stocks after the simulation is complete and one for the value of your stocks after you’ve been truncating to three decimal places at each step. Start by initializing these variables to >>>
Now let’s run the simulation for 1,000,000 seconds (approximately 11.5
days). For each second, generate a random value between >>>
The meat of the simulation takes place in the At each step of the loop, a new random number between As you can see by
inspecting the Ignoring for the moment that >>>
What a difference! Shocking as it may seem, this exact error caused quite a stir in the early 1980s when the system designed for recording the value of the Vancouver Stock Exchange truncated the overall index value to three decimal places instead of rounding. Rounding errors have swayed elections and even resulted in the loss of life. How you round numbers is important, and as a responsible developer and software designer, you need to know what the common issues are and how to deal with them. Let’s dive in and investigate what the different rounding methods are and how you can implement each one in pure Python. A Menagerie of MethodsThere are a plethora of rounding strategies, each with advantages and disadvantages. In this section, you’ll learn about some of the most common techniques, and how they can influence your data. TruncationThe simplest, albeit crudest, method for rounding a number is to truncate the number to a given number of digits. When you truncate a number, you replace each digit after a given position with 0. Here are some examples:
You’ve already seen one way to implement this in the
You can generalize this process by replacing
In this version of The >>>
You can even pass a negative number to >>>
When you truncate a positive number, you are rounding it down. Likewise, truncating a negative number rounds that number up. In a sense, truncation is a combination of rounding methods depending on the sign of the number you are rounding. Let’s take a look at each of these rounding methods individually, starting with rounding up. Rounding UpThe second rounding strategy we’ll look at is called “rounding up.” This strategy always rounds a number up to a specified number of digits. The following table summarizes this strategy:
To implement the “rounding up” strategy in Python, we’ll use the The Every number
that is not an integer lies between two consecutive integers. For example, the number In mathematics, a special function called the ceiling function maps every number to its ceiling. To allow the ceiling function
to accept integers, the ceiling of an integer is defined to be the integer itself. So the ceiling of the number In Python, >>>
Notice that the ceiling of Let’s write a function called
You may notice that This pattern of shifting the decimal point, applying some rounding method to round to an integer, and then shifting the decimal point back will come up over and over again as we investigate more rounding methods. This is, after all, the mental algorithm we humans use to round numbers by hand. Let’s look at how well >>>
Just like
>>>
When you pass a negative number to Take a guess at what >>>
Is If you
examine the logic used in defining Let’s establish some terminology. For our purposes, we’ll use the terms “round up” and “round down” according to the following diagram: Round up to the right and down to the left. (Image: David Amos)Rounding up always rounds a number to the right on the number line, and rounding down always rounds a number to the left on the number line. Rounding DownThe counterpart to “rounding up” is the “rounding down” strategy, which always rounds a number down to a specified number of digits. Here are some examples illustrating this strategy:
To implement the “rounding down” strategy in Python, we can follow the same algorithm we used for both In Lucky
for us, the >>>
Here’s the definition of
That looks just like You can test
>>>
The effects of Before we discuss any more rounding strategies, let’s stop and take a moment to talk about how rounding can make your data biased. Interlude: Rounding BiasYou’ve now seen three rounding methods: There is one important difference between Recall that On the other hand, the The concept of symmetry introduces the notion of rounding bias, which describes how rounding affects numeric data in a dataset. The “rounding up” strategy has a round towards positive infinity bias, because the value is always rounded up in the direction of positive infinity. Likewise, the “rounding down” strategy has a round towards negative infinity bias. The “truncation” strategy exhibits a round towards negative infinity bias on positive values and a round towards positive infinity for negative values. Rounding functions with this behavior are said to have a round towards zero bias, in general. Let’s see how this works in practice. Consider the following list of floats: >>>
Let’s compute the mean value of the values in >>>
Now apply each of >>>
After every number in This example does not imply that you should always truncate when you need to round individual values while preserving a mean value as closely as possible. The What this example does illustrate is the effect rounding bias has on values computed from data that has been rounded. You will need to keep these effects in mind when drawing conclusions from data that has been rounded. Typically, when rounding, you are interested in rounding to the nearest number with some specified precision, instead of just rounding everything up or down. For example, if someone asks you to round the numbers What about the number The way that most people are taught break ties is by rounding to the greater of the two possible numbers. Rounding Half UpThe “rounding half up” strategy rounds every number to the nearest number with the specified precision, and breaks ties by rounding up. Here are some examples:
To implement the “rounding half up” strategy in Python, you start as usual by shifting the decimal point to the right by the desired number of places. At this point, though, you need a way to determine if the digit just after the shifted decimal point is less than or greater than or equal to One way to do this is to add
Here’s what this looks like in Python:
Notice that Let’s test >>>
Since >>>
Great! You can now finally get that result that the built-in >>>
Before you get too excited though, let’s see what happens when you try and round >>>
Wait. We just discussed how ties get rounded to the greater of the two possible values. Is there a bug in the When >>>
Well… that’s wrong! But it does explain why >>>
Even though Well, now you know how The fact that Python says that Floating-point numbers do not have exact precision, and therefore should not be used in situations where precision is paramount. For applications where the exact precision is necessary, you can use the If you have determined that Python’s standard Now that you’ve gotten a taste of how machines round numbers in memory, let’s continue our discussion on rounding strategies by looking at another way to break a tie. Rounding Half DownThe “rounding half down” strategy rounds to the nearest number with the desired precision, just like the “rounding half up” method, except that it breaks ties by rounding to the lesser of the two numbers. Here are some examples:
You can implement the “rounding half down” strategy in Python by replacing
Let’s check >>>
Both >>>
Let’s compute the mean of these numbers: >>>
Next, compute the mean on the data after rounding to one decimal place with >>>
Every number in
The remaining rounding strategies we’ll discuss all attempt to mitigate these biases in different ways. Rounding Half Away From ZeroIf you examine >>>
One way to introduce symmetry is to always round a tie away from zero. The following table illustrates how this works:
To implement the “rounding half away from zero” strategy on a number
After rounding according to one of the above four rules, you then shift the decimal place back to the left. Given a number
That’s easy enough, but there’s actually a simpler way! If you first take the
absolute value of
>>>
Notice that Using
In Checking >>>
The Let’s check how well >>>
The mean value of the numbers in However, How do you handle situations where the number of positive and negative ties are drastically different? The answer to this question brings us full circle to the function that deceived us at the beginning of this article: Python’s built-in Rounding Half To EvenOne way to mitigate rounding bias when rounding values in a dataset is to round ties to the nearest even number at the desired precision. Here are some examples of how to do that:
The “rounding half to even strategy” is the strategy used by Python’s built-in Now you know why To prove to yourself that >>>
The Finally, >>>
You shouldn’t be concerned with these occasional errors if floating-point precision is sufficient for your application. When precision is paramount, you should use Python’s The Decimal ClassPython’s decimal module is one of those
“batteries-included” features of the language that you might not be aware of if you’re new to Python. The guiding principle of the
The benefits of the
Let’s explore how rounding works in the >>>
As you can see in the example above, the default rounding strategy for the Let’s declare a number using the >>>
Just for fun, let’s test the assertion that >>>
Ahhh. That’s satisfying, isn’t it? Rounding a >>>
Okay, that probably looks a little funky, so
let’s break that down. The Recall that the >>>
Another benefit of the >>>
To change the precision, you call The exact value of To change the default rounding strategy, you can set the
The first thing to notice is that the naming scheme used by the Secondly, some of the rounding strategies mentioned in the table may look unfamiliar since we haven’t discussed them. You’ve already seen how The >>>
Notice that the results of The >>>
Like The
>>>
The There are three strategies in the >>>
Notice that There is also a >>>
The final rounding strategy available in the >>>
In the above examples, it looks as if >>>
In the first example, the number In this section, we have only focused on the rounding aspects of the For more information on Next, let’s turn our attention to two staples of Python’s scientific computing and data science stacks: NumPy and Pandas. Rounding NumPy ArraysIn the domains of data science and scientific computing, you often store your data as a NumPy Let’s generate some data by creating a 3×4 NumPy array of pseudo-random numbers: >>>
First, we seed the To round all of the values in the For example, the following rounds all of the values in >>>
For example, the value in the third row of the first column in the If you need to round the data in your array to integers, NumPy offers several options:
The >>>
Hey, we discovered a new number! Negative zero! Actually, the IEEE-754 standard requires the implementation of both a positive and negative zero. What possible use is there for something like this? Wikipedia knows the answer:
To round every value down to the nearest integer, use >>>
You can also truncate each value to its integer component with >>>
Finally, to round to the nearest
integer using the “rounding half to even” strategy, use >>>
You might have noticed that a lot of the rounding strategies we discussed earlier are missing here. For the vast majority of situations, the
Thanks to NumPy’s vectorized operations, this works just as you expect: >>>
Now that you’re a NumPy rounding master, let’s take a look at Python’s other data science heavy-weight: the Pandas library. Rounding Pandas Series and DataFrameThe Pandas library has become a staple for data scientists and data analysts who work in Python. In the words of Real Python’s own Joe Wyndham:
The two main Pandas data structures are the >>>
The >>>
If you need more rounding flexibility, you can apply NumPy’s >>>
The modified >>>
Congratulations,
you’re well on your way to rounding mastery! You now know that there are more ways to round a number than there are taco combinations. (Well… maybe not!) You can implement numerous rounding strategies in pure Python, and you have sharpened your skills on rounding NumPy arrays and Pandas There’s just one more step: knowing when to apply the right strategy. Applications and Best PracticesThe last stretch on your road to rounding virtuosity is understanding when to apply your newfound knowledge. In this section, you’ll learn some best practices to make sure you round your numbers the right way. Store More and Round LateWhen you deal with large sets of data, storage can be an issue. In most relational databases, each column in a table is designed to store a specific data type, and numeric data types are often assigned precision to help conserve memory. For example, a temperature sensor may report the temperature in a long-running industrial oven every ten seconds accurate to eight decimal places. The readings from this are used to detect abnormal fluctuations in temperature that could indicate the failure of a heating element or some other component. So, there might be a Python script running that compares each incoming reading to the last to check for large fluctuations. The readings from this sensor are also stored in a SQL database so that the daily average temperature inside the oven can be computed each day at midnight. The manufacturer of the heating
element inside the oven recommends replacing the component whenever the daily average temperature drops For this calculation, you only need three decimal places of precision. But you know from the incident at the Vancouver Stock Exchange that removing too much precision can drastically affect your calculation. If you have the space available, you should store the data at full precision. If storage is an issue, a good rule of thumb is to store at least two or three more decimal places of precision than you need for your calculation. Finally, when you compute the daily average temperature, you should calculate it to the full precision available and round the final answer. Obey Local Currency RegulationsWhen you order a cup of coffee for $2.40 at the coffee shop, the merchant typically adds a required tax. The amount of that tax depends a lot on where you are geographically, but for the sake of argument, let’s say it’s 6%. The tax to be added comes out to $0.144. Should you round this up to $0.15 or down to $0.14? The answer probably depends on the regulations set forth by the local government! Situations like this can also arise when you are converting one currency to another. In 1999, the European Commission on Economical and Financial Affairs codified the use of the “rounding half away from zero” strategy when converting currencies to the Euro, but other currencies may have adopted different regulations. Another scenario, “Swedish rounding”, occurs when the minimum unit of currency at the accounting level in a country is smaller than the lowest unit of physical currency. For example, if a cup of coffee costs $2.54 after tax, but there are no 1-cent coins in circulation, what do you do? The buyer won’t have the exact amount, and the merchant can’t make exact change. How situations like this are handled is typically determined by a country’s government. You can find a list of rounding methods used by various countries on Wikipedia. If you are designing software for calculating currencies, you should always check the local laws and regulations in your users’ locations. When In Doubt, Round Ties To EvenWhen you are rounding numbers in large datasets that are used in complex computations, the primary concern is limiting the growth of the error due to rounding. Of all the methods we’ve discussed in this article, the “rounding half to even” strategy minimizes rounding bias the best. Fortunately, Python, NumPy, and Pandas all default to this strategy, so by using the built-in rounding functions you’re already well protected! SummaryWhew! What a journey this has been! In this article, you learned that:
If you are interested in learning more and digging into the nitty-gritty details of everything we’ve covered, the links below should keep you busy for quite a while. At the very least, if you’ve enjoyed this article and learned something new from it, pass it on to a friend or team member! Be sure to share your thoughts with us in the comments. We’d love to hear some of your own rounding-related battle stories! Happy Pythoning! Additional ResourcesRounding strategies and bias:
Floating-point and decimal specifications:
Interesting Reads:
How do you round to the nearest in Python?To round to the nearest whole number in Python, you can use the round() method. You should not specify a number of decimal places to which your number should be rounded. Our Python code returns: 24 . The round() function is usually used with floating-point numbers, which include decimal places.
How do you round to the nearest tenth?To round the decimal number to its nearest tenth, look at the hundredth number. If that number is greater than 5, add 1 to the tenth value. If it is less than 5, leave the tenth place value as it is, and remove all the numbers present after the tenth's place.
How does round () work in Python?Python round() Function
The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.
How do you round a number to the nearest multiple of 10 in Python?To round number to nearest 10, use round() function. We can divide the value by 10, round the result to zero precision, and multiply with 10 again. Or you can pass a negative value for precision. The negative denotes that rounding happens to the left of the decimal point.
|