Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Round Function in Python?
3.
Python round() Syntax
4.
Python round() Function Parameters
4.1.
Python
5.
Python round() Function Return Value
5.1.
Example
5.2.
Implementation in Python
5.3.
Python
5.3.1.
 
5.3.2.
Output
5.4.
Implementation in Python
5.5.
Python
5.5.1.
 
5.5.2.
Output
6.
Round() Function Example with Float Numbers
6.1.
Python
7.
Round() Function Example with Integer Values
7.1.
Python
8.
Round() Function Example with Negative Numbers
8.1.
Python
9.
Round() Function Example with Numpy Arrays
9.1.
Python
10.
Round() Function Example with Decimal Module
10.1.
Python
10.2.
Error and Exceptions
11.
Practical Applications
12.
Frequently Asked Questions
12.1.
Why is round 2.5 is 2 in Python?
12.2.
How do you round up to 0.5 in Python?
12.3.
What does the round () function return?
12.4.
How do you use round formula?
13.
Conclusion
Last Updated: Mar 28, 2024
Easy

Round() function in Python

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

We, humans, like things that are simple, easy to make sense of, that are easy to understand. And for us, it's harder to use just any decimal number in calculations, even while calculating length or while calculating our weight on the weighing machine. Hence we generally prefer to use round numbers.

Round() function in Python

In this blog, we will study the round() function in Python. It is a function that helps to round off a number and eliminates the least significant digits. This simplifies the notation while keeping very close to the original value.

Must read, Divmod in Python, and Convert String to List Python

What is Round Function in Python?

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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))

This will produce the following output:

4
4.208
4.2078

Python round() Function Return Value

The round() function returns the-

  • If the value of digits is not provided, the round function will return the nearest integer to the given number. 
  • The number is rounded off to the given digits if the digits parameter is provided.

Example

The number 3.5, when rounded to the nearest whole number digit, is 4. Similarly, for 1.6, it will be 2.

Input
3.5
1.6
Output
4
2

Now let's practice some examples of the round() function when the second parameter is not defined.

Implementation in Python

  • Python

Python

# integers
print(round(10))
print(round(25))


# floating point
print(round(13.3))
print(round(13.5))
print(round(13.6))

 

Output

output1

Now it's time to practice some examples of the round() function when the second parameter is given. You can compile it with online python compiler.

Implementation in Python

  • Python

Python

# when the last digit is less than 5
print(round(4.583, 2))
print(round(4.5834, 3))


# when the last digit is equal to 5
print(round(4.585, 2))
print(round(4.555, 1))


# when the last digit is greater than 5
print(round(4.587, 2))
print(round(4.6, 1))

 

Output

output2

Round() Function Example with Float Numbers

  • Python

Python

# Round a float number to two decimal places
num = 3.14159
rounded_num = round(num, 2)
print(rounded_num) # Output: 3.14

# Round a float number to the nearest integer
num2 = 3.7
rounded_num2 = round(num2)
print(rounded_num2) # Output: 4

# Round a float number using the decimal module
import decimal
num3 = decimal.Decimal('3.14159')
rounded_num3 = round(num3, 2)
print(rounded_num3) # Output: 3.14

Round() Function Example with Integer Values

  • Python

Python

# Round an integer value to the nearest multiple of 10
num1 = 45
rounded_num1 = round(num1, -1)
print(rounded_num1) # Output: 50

# Round an integer value to the nearest multiple of 100
num2 = 356
rounded_num2 = round(num2, -2)
print(rounded_num2) # Output: 400

# Round an integer value to the nearest 5
num3 = 23
rounded_num3 = round(num3 / 5) * 5
print(rounded_num3) # Output: 25

Round() Function Example with Negative Numbers

  • Python

Python

# 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

Round() Function Example with Numpy Arrays

  • Python

Python

import numpy as np
# Create a NumPy array with float values
arr = np.array([1.234, 5.678, 9.012])
# Round the array to two decimal places
rounded_arr = np.round(arr, 2)
# Print the original and rounded arrays
print(arr) # Output: [1.234 5.678 9.012]
print(rounded_arr) # Output: [1.23 5.68 9.01]

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_CEILINGIt 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_DOWNIt will round to the nearest with ties going toward zero.
ROUND_HALF_EVENIt will round to the nearest value heading to the nearest even integer.
ROUND_HALF_UPIt will round to the nearest value, with the value going away from 0(zero).
ROUND_UPIt will round up to where the value of the floating point will go away from zero.
ROUND_05UPIt 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))

Output:

output

Error and Exceptions

How the errors and exceptions can occur when using the round() function in Python:

  1. 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.

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.

Check this out, Fibonacci Series in Python and Quicksort Python.

Frequently Asked Questions

Why is round 2.5 is 2 in Python?

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.

How do you round up to 0.5 in Python?

We can round up to the nearest 0.5 in Python using the round() function with some simple arithmetic. For example, we can round up number 2.3, by doing round(2.3 * 2) / 2 this will produce a result of 2.5.

What does the round () function return?

The round() function in Python returns a rounded version of a number. The exact return value depends on the arguments provided to the function.

How do you use round formula?

In Python, you can use the built-in round() function to round a number. The syntax is round(number, ndigits). number is the value you want to round, and ndigits is the number of decimals you want in your rounded value. If ndigits is omitted, it rounds to the nearest integer.

Conclusion

This article taught us to calculate the Round() function in Python. We have discussed the approach using some examples in python languages. To enhance your knowledge of python programming, check out these articles-

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Keep Coding!