Python Round off Techniques | Python round() Function

A rounded number has about the same value as the number you start with, but it is less exact. The Python round is also similar and works in the same way as it works in Mathematics.
For example, 341.7 rounded to the nearest 342. That is because 341.7 is closer in value to 342 than to 341. When rounding off to the nearest dollar, $1.89 becomes $2.00, because $1.89 is closer to $2.00 than to $1.00.

You can round a number or more specifically a float number. There are several ways to do Python round off. One of the most common ways is using the round() method.
So in this post, we will cover all the three methods to Python Round a number which is the following:

  1. Python rounds off number using the round() function.
  2. Python round by using the format().
  3. Using math.floor() function
  4. Using math.ceil() method

Python Round Using round() Function

The round() function is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input.

If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

Syntax of round() Function

The syntax for the round() function is as follows:

round(number, digits)

Parameters of round()

NameDescriptionRequired /
Optional
numberThis parameter represents the number to be rounded. Required
digitsIt is the optional parameter that represents the number of decimals to use when rounding the number. Default is 0.Optional

The return type of round() Function

This round() function in Python returns a floating-point number after rounding off the specified number, with the specified number of decimals.

Pictorial Presentation of How round() Function Works in Python

Pictorial Presentation of Python round() Function

Examples of Python round() Function

Let’s see some examples to round off floating-point numbers in Python.
In these different examples, we will learn the rounding off of a floating-point number with the explanation.

Example 1: Python Example to Implement round() Function When Second Parameter is Missing

Below is the python implementation of the round() function if the second parameter is missing.

# for integers
print(round(8))

# for floating point number when decimal value is greater than 5
print(round(21.7))

# for floating point number when decimal value is less than 5
print(round(11.3))

# for floating point number when decimal value is equal to 5
print(round(4.5))

Output:

8
22
11
4

Example 2: Python Example to Implement round() Function When Second Parameter is Present

Now, if the second parameter is present. What will be the output? Let’s see in the below examples.

# when the last digit is = 5 
print(round(5.945, 2)) 

# when the last digit is > 5 
print(round(5.948, 2)) 

# when the last digit is < 5 
print(round(5.942, 2)) 

Output:

5.95
5.95
5.94

In the above example, we have taken three numbers 5.945, 5.948 and 5.942. And we are limiting floats to two decimal point number. The last digits of these three numbers are equal to 5, greater than 5 and less than 5.

So if the last digit is equal to 5 the number will round off to 5.95. If the last digit of the number is greater than 5 the number will also be round off to 5.95. But if the last digit is less than 5 the number will round off to 5.94.

Example 3: Python Example to Implement round() Function When Second Parameter is Negative Number

ndigits can be negative numbers as well. It allows you to e.g. round numbers to ten’s or hundreds.

# Round to ten's
#Example: 1
first = round(74, -1)
print(first) 

#Example: 2
second = round(165, -1)
print(second)

# Round to hundred's
#Example: 1
third = round(448, -2)
print(third)

#Example: 2
fourth = round(628, -2)
print(fourth)

Output:

70
160
400
600

Here in the above example if we use ndigit as -1 it will round-off to the nearest ten’s number. And if we use -2 as the ndigit it will round off to the nearest hundredth number.

Example 4: Python Example to Round off a List of Floating-Point Numbers

list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].

In the following example, a list of float items is created. This is followed by using the for loop to iterate through the list items and executing the round function on each item. The rounded items are added to a new list and displayed, have a look:

float_lst = [31.56, 84.9, 7.632, 49.9, 80.35]
 
rounded_list = [round(x) for x in float_lst]
 
print("List before applying the round: ",float_lst)
 
print("List after round function is applied: ",rounded_list)

Output:

List before applying the round:  [31.56, 84.9, 7.632, 49.9, 80.35]
List after round function is applied:  [32, 85, 8, 50, 80]

In the above example, we rounded off all the elements of the entire list float_lst.

Example 5: Round off Numpy Arrays using Python numpy.round()

NumPy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

To solve this, we can make use of NumPy module and use numpy.round() or numpy.around() method, as shown in the example below.

import numpy as np

arr = [-0.964511, 4.75598989, 11.6955323, -0.8642326, 126.548632, -15.323]

print(np.round(arr, 2))

Output:

[ -0.96   4.76  11.7   -0.86   126.55   -15.32]

Note:

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n-digits. If two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.

Error and Exceptions

TypeError: This error is raised in the case when there is anything other than numbers in the parameters.

Python Round Using format() Method

str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.

Using a Single Formatter :

Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function.

Syntax : { } .format(value)

Parameters :
(value) : Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype : Returns a formatted string with the value passed as parameter in the placeholder position.

Number Formatting

The following table shows various ways to format numbers using Python’s str.format(), including examples for both float formatting and integer formatting.

To run examples use: print("FORMAT".format(NUMBER));

To get the output of the first example, formatting afloat to two decimal places, you would run:

print("{:.2f}".format(3.1415926));

NumberFormatOutputDescription
3.1415926{:.2f}3.14Format float 2 decimal places
3.1415926{:+.2f}+3.14Format float 2 decimal places with a sign
-1{:+.2f}-1.00Format float 2 decimal places with a sign
2.71828{:.0f}3Format float with no decimal places
5{:0>2d}05Pad number with zeros (left padding, width 2)
5{:x<4d}5xxxPad number with x’s (right padding, width 4)
10{:x<4d}10xxPad number with x’s (right padding, width 4)
1000000{:,}1,000,000Number format with a comma separator
0.25{:.2%}25.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
13{:10d}        13Right aligned (default, width 10)
13{:<10d}13Left aligned (width 10)
13{:^10d}    13Center aligned (width 10)

Example of Python Format to Round a Floating Point Number:

# Convert base-10 decimal integers 
# to floating point numeric constants 
print ("This site is {0:f}% securely {1}!!".format(100, "encrypted")) 

# To limit the precision 
print ("My average of this {0} was {1:.2f}%".format("semester", 78.234876)) 

# For no decimal places 
print ("My average of this {0} was {1:.0f}%".format("semester", 78.234876)) 

# Convert an integer to its binary or 
# with other different converted bases. 
print("The {0} of 100 is {1:b}".format("binary", 100)) 
		
print("The {0} of 100 is {1:o}".format("octal", 100)) 

Output:

This site is 100.000000% securely encrypted!!
My average of this semester was 78.23%
My average of this semester was 78%
The binary of 100 is 1100100
The octal of 100 is 144

Note:

if the goal of rounding a number is to add it to a string, a solution is to use format().

Python Round Using math.floor() Function

In Python, the math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If the number is already an integer, the same number is returned.

Syntax: math.floor(x)

Parameter:
x: This is a numeric expression.

Returns:  largest integer not greater than x.

Python Floor Function Example

The floor Function in Python is used to return the closest integer value which is less than or equal to given numeric value.

Let me show you a simple example of floor function that returns the closet value of 12.95

# Python floor function example
 
import math
 
val = math.floor(12.95)
print(val)

Output:

# Python floor function example
 
import math
 
val = math.floor(12.95)
print(val)

Python Round Using math.ceil() Method

In Python, the math module contains a number of mathematical operations, which can be performed with ease using the module. math.ceil() the function returns the smallest integral value greater than the number. If the number is already an integer, the same number is returned.

Syntax: math.ceil(x)

Parameter:
x: This is a numeric expression.

Returns:  Smallest integer not less than x.

Python ceil Function to Round off Example

The Python ceil Function allows you to find the smallest integer value, which is greater than or equal to the numeric values. In this example, We are going to find the ceiling values of different data types and display the output.

# Python CEIL Function Example

import math

Tup = (10.98, 20.26, 30.05, -40.95 , 50.45) # Tuple Declaration
Lis = [-10.98, 32.65, -39.59, -42.15 , 35.97] # List Declaration

print('Ceiling value of Positive Number = %.2f' %math.ceil(10))
print('Ceiling value of Negative Number = %.2f' %math.ceil(-15))

print('Ceiling value of Tuple Item = %.2f' %math.ceil(Tup[2]))
print('Ceiling value of List Item = %.2f' %math.ceil(Lis[2]))

print("The Value of 'PI' after the Ceil function is: ", math.ceil(math.pi))

print('Ceiling value of Multiple Number = %.2f' %math.ceil(10 + 20 - 40.65))

print('Ceiling value of String Number = ', math.ceil('Python'))

Output:

Ceiling value of Positive Number = 10.00
Ceiling value of Negative Number = -15.00
Ceiling value of Tuple Item = 31.00
Ceiling value of List Item = -39.00
The Value of 'PI' after the Ceil function is:  4
Ceiling value of Multiple Number = -10.00
Traceback (most recent call last):
  File "c:/Users/Karan/Desktop/test.py", line 18, in <module>
    print('Ceiling value of String Number = ', math.ceil('Python'))
TypeError: must be real number, not str

In the above example you can see there is a type error. When we apply the ceil() function to the string.

So Here point to be noted is that the ceil() Function can round-off only the numerical values in Python.

Must Read:

Conclusion

You can use the Python round function to round a number to a certain decimal place. This can be helpful if you’re working with mathematical calculations that return numbers with unnecessary decimal places, or if you are working with values like money which typically do not show more than two decimal places.

In this tutorial, we discussed how to use the round() function to round numbers in Python. We then explored other methods like format(), floor(), and ceil() to round off the numbers in python programming. Now you’re ready to start rounding numbers in Python like an expert!

Try to run the programs on your side and let me know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments