Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The `round()` function in Python rounds a number to a specified number of decimal places. It takes two arguments: the number to be rounded and an optional argument specifying the number of decimal places (default is 0). The function returns the rounded number. If the decimal part is .5 or greater, it rounds up; otherwise, it rounds down. For example, `round(3.14159, 2)` returns `3.14`. In this article, we will discuss the round function in detail with proper code example.
The round() function in Python is a built-in function that allows you to round a number to a specified number of decimal places or to the nearest integer. It takes two arguments: the number you want to round, and the number of decimal places you want to round to. If you omit the second argument, it defaults to zero, and the number is rounded to the nearest integer. The round() function uses the rounding half to even method by default, which means that if the number you're rounding is exactly halfway between two possible rounding values, the result is rounded to the nearest even number. This behaviour can be changed by specifying a different rounding method using the decimal module. The round() function is useful when you need to perform calculations that require precision and rounding of decimal values.
Python round() Syntax
round(number, ndigits)
>>> round(3.14159) # round to the nearest integer as ndigits is not provided
3
Python round() Function Parameters
As we can see in the syntax that there are two parameters i.e., number and ndigits. The number parameter is the value that you want to round. It can be an integer or a floating-point number. The ndigits parameter is optional. It specifies the number of decimal places to which you want to round the number. If ndigits is not provided, the round() function will round the number to the nearest whole number. Let us take an example to understand round() with a single parameter and two parameters:
Python
Python
val = 4.2078
# round() with single parameter print(round(val))
# round() with two parameters print(round(val, 3)) print(round(val, 4))
You can also try this code with Online Python Compiler
# Round a negative float number to two decimal places num1 = -3.14159 rounded_num1 = round(num1, 2) print(rounded_num1) # Output: -3.14 # Round a negative integer value to the nearest multiple of 10 num2 = -45 rounded_num2 = round(num2, -1) print(rounded_num2) # Output: -50 # Round a negative float number to the nearest integer num3 = -3.7 rounded_num3 = round(num3) print(rounded_num3) # Output: -4
You can also try this code with Online Python Compiler
Apart from this, there are more unique ways to round a number. This python decimal module helps in handling decimal numbers more accurately. Let's discuss a few of them.
ROUND_CEILING
It will round towards infinity or round up.
ROUND_DOWN:
It will round the value towards zero or truncate.
ROUND_FLOOR:
It will round towards -infinity or round down.
ROUND_HALF_DOWN
It will round to the nearest with ties going toward zero.
ROUND_HALF_EVEN
It will round to the nearest value heading to the nearest even integer.
ROUND_HALF_UP
It will round to the nearest value, with the value going away from 0(zero).
ROUND_UP
It will round up to where the value of the floating point will go away from zero.
ROUND_05UP
It will round up whether the last digit is 0 or 5. Otherwise, it will round down.
Round() Function Example with Decimal Module
The Decimal module is employed for performing tasks related to decimal floating-point operations, ensuring precise rounding. To utilize it, we must begin by importing it from the standard library module Decimal. Here's an example of using the round() function with the decimal module in Python.
Python
Python
import decimal from decimal import Decimal from decimal import getcontext
# Set precision for Decimal operations to 3 decimal places getcontext().prec = 3
# Set rounding mode to ROUND_FLOOR getcontext().rounding = decimal.ROUND_FLOOR print ("Result of ROUND_FLOOR = ",Decimal(2.617) + Decimal(0))
# Set rounding mode to ROUND_HALF_UP getcontext().rounding = decimal.ROUND_HALF_UP print ("Result of ROUND_HALF_UP = ",Decimal(8.685) + Decimal(0))
You can also try this code with Online Python Compiler
How the errors and exceptions can occur when using the round() function in Python:
TypeError example:
>>> round('3.14')
TypeError: type str doesn't define __round__ method
Here, we are trying to round a string value, which is not possible. This results in a TypeError exception.
2. ValueError example:
>>> round(3.14159, '2')
ValueError: ndigits must be an integer
In this case, we passed a non-integer value as the second argument to the round() function. This causes a ValueError exception to be raised.
3. OverflowError example:
>>> round(10**1000)
OverflowError: int too large to convert to float
In this case, we passed a very large integer value to the round() function, which cannot be represented as a floating-point number. This causes an OverflowError exception to be raised.
4. NameError example:
>>> round(3.14159)
NameError: name 'round' is not defined
Here, we are trying to use the round() function without importing it first. This results in a NameError exception.
Python round() with Negative Integers
The `round()` function can also accept negative integers as the second argument. When a negative integer is provided, it rounds the number to the nearest multiple of 10 raised to the power of the negative integer.
1. `round(num, -1)` rounds the number `1234.5678` to the nearest multiple of 10^(-1), which is 10. The result is `1230.0`.
2. `round(num, -2)` rounds the number `1234.5678` to the nearest multiple of 10^(-2), which is 100. The result is `1200.0`.
3. `round(num, -3)` rounds the number `1234.5678` to the nearest multiple of 10^(-3), which is 1000. The result is `1000.0`.
Using a negative integer as the second argument in `round()` allows you to round the number to the nearest multiple of a power of 10. The magnitude of the negative integer determines the number of digits to the left of the decimal point that will be considered for rounding.
Round Number with Math Library in Python
In Python, you can also use the `math` library to perform rounding operations. The `math` library provides two functions for rounding: `math.floor()` and `math.ceil()`.
1. `math.floor(x)`: This function rounds down the number `x` to the nearest integer less than or equal to `x`.
Example:
Python
Python
import math
num = 3.14159 rounded_down = math.floor(num) print(rounded_down) # Output: 3
You can also try this code with Online Python Compiler
In this example, `math.ceil(3.14159)` rounds up the number to the nearest integer greater than or equal to 3.14159, which is 4.
The `math.floor()` and `math.ceil()` functions always return an integer value, as opposed to the built-in `round()` function, which returns a value of the same type as the input (integer or float).
It's important to note that to use these functions, you need to import the `math` library at the beginning of your Python script using `import math`.
Examples of Practical Applications
The round() function in Python is a useful tool for handling numerical data and performing mathematical calculations. Here are some practical applications of the round() function in Python:
Financial calculations: In financial applications, it is often necessary to round numbers to a certain number of decimal places. For example, when calculating interest rates or currency conversions, you may need to round values to two decimal places. The round() function is ideal for this purpose.
Data analysis: When working with large data sets, it is often necessary to round data to a certain number of decimal places. This can help to reduce noise in the data and make it easier to work with. The round() function is commonly used in data analysis for this purpose.
Scientific calculations: In scientific applications, it is important to perform calculations with a high degree of precision. The round() function can be used to round values to a certain number of decimal places to achieve this level of precision.
User interfaces: In user interfaces, it is often necessary to display numerical data to the user in a user-friendly format. The round() function can be used to format numerical values in a way that is easy for the user to read and understand.
Overall, the round() function is a versatile tool that can be used in a wide range of applications where numerical data is involved.
In Python, round(2.5) results in 2 because it uses the "round half to even" or "banker's rounding" method, which rounds to the nearest even number in case of a tie.
Does Python round 0.5 up or down?
Python's round() function uses the "round half to even" strategy. It rounds 0.5 to the nearest even number, so 0.5 rounds to 0.
What does round() do in Python?
The round() function in Python rounds a floating-point number to a specified number of decimal places or the nearest integer by default.
Conclusion
In this article, we talked about the `round()` function in Python, which is used to round numbers to a specified number of decimal places. We also discussed how `round()` works with negative integers and how the `math` library provides additional rounding functions. Rounding is a versatile operation with practical applications in various domains, including finance, science, and data analysis.