Open In App

How to Round Numbers in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss How to Round Numbers in Python with suitable methods and examples of How to round up in Python.

Example:

Input: 3.5
Output: 4
Explanation: Nearest whole number.

Input: 3.74
Output: 3.7
Explanation: Rounded to one decimal place.

Round Up Numbers in Python

Rounding a number means making the number simpler by keeping its value intact but closer to the next number. There are various methods to round numbers in Python here we are discussing some generally used for How to round up in Python, Below are the following points that will be covered in this article using Python:

Round Numbers in Python using Built-in round() Function

In Python, there is a built-in round() function that rounds off a number to the given number of digits. The function round() accepts two numeric arguments, n, and n digits, and then returns the number n after rounding it to n digits. If the number of digits is not provided for rounding off, the function rounds off the given number n to the nearest integer. 

Example :In this example the below code showcases the `round()` function for integers and floating-point numbers. It also illustrates rounding to two decimal places, demonstrating cases where the next digit is 5, greater than 5, and less than 5.

python3




# For integers
print(round(11))
 
# For floating point
print(round(22.7)) 
 
# if the second parameter is present
 
# when the (ndigit+1)th digit is =5
print(round(4.465, 2))
   
# when the (ndigit+1)th digit is >=5
print(round(4.476, 2))  
   
# when the (ndigit+1)th digit is <5
print(round(4.473, 2))


Output: 

11
23
4.46
4.48
4.47

Round Numbers in Python using Truncation concept

In this function, each digit after a given position is replaced with 0. python truncate() function can be used with positive as well as negative numbers. The truncation function can be implemented in the following way:

  • Multiplying the number by 10^p (10 raised to the pth power) to shift the decimal point p places to the right.
  • Taking the integer part of that new number using int().
  • Shifting the decimal place p places back to the left by dividing by 10^p.

python3




# defining truncate function
# second argument defaults to 0
# so that if no argument is passed
# it returns the integer part of number
 
def truncate(n, decimals = 0):
    multiplier = 10 ** decimals
    return int(n * multiplier) / multiplier
 
print(truncate(16.5))
print(truncate(-3.853, 1))
print(truncate(3.815, 2))
 
# we can truncate digits towards the left of the decimal point
# by passing a negative number.
print(truncate(346.8, -1))
print(truncate(-2947.48, -3))


Output: 

16.0
-3.8
3.81
340.0
-2000.0

Round Numbers in Python using Math.ceil() and Math.floor() functions

Math.ceil(): This function returns the nearest integer that is greater than or equal to a given number. 
Math.floor(): This function returns the nearest integer less than or equal to a given number. 

Example :In this example the below code utilizes the `math` library to compute ceiling values for positive and negative decimals with `math.ceil` and floor values with `math.floor`. Outputs are 5, 0, 2, and -1 for the respective cases.

python3




# import math library
import math
 
# ceil value for positive
# decimal number
print(math.ceil(4.2))
 
# ceil value for negative
# decimal number
print(math.ceil(-0.5))
 
# floor value for decimal
# and negative number
print(math.floor(2.2))
print(math.floor(-0.5))


Output: 

5
0
2
-1

Round Numbers in Python using math.ceil

Rounding up a number involves shifting the decimal point to the right, rounding up, and then shifting it back to the left for precision using `math.ceil()` and multiplication/division operations.

Example :In this example the below code defines a `round_up` function using the `math` library, which rounds a number to a specified decimal place. It utilizes multiplication, rounding with `math.ceil()`, and division for precision. Positive and negative values are tested for rounding.

python3




# import math library
import math
 
# define a function for
# round_up
def round_up(n, decimals = 0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier
 
# passing positive values
print(round_up(2.1))
print(round_up(2.23, 1))
print(round_up(2.543, 2))
 
# passing negative values
print(round_up(22.45, -1))
print(round_up(2352, -2))


Output: 

3.0
2.3
2.55
30.0
2400.0

We can follow the diagram below to understand round up and round down. Round up to the right and down to the left. 

Understanding Rounding Up and Rounding Down

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. 

Round Numbers in Python using math.floor 

In Rounding Down a number is rounded down to a specified number of digits. The rounding down function can be implemented in the following way: 

  • First, the decimal point in n is shifted to the correct number of places to the right by multiplying n by 10 ** decimals.
  • The new value is rounded up to the nearest integer using math.floor().
  • Finally, the decimal point is shifted back to the left by dividing by 10 ** decimals.

python3




import math
 
# defining a function for
# round down.
def round_down(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier) / multiplier
 
# passing different values to function
print(round_down(2.5))
print(round_down(2.48, 1))
print(round_down(-0.5))


Output: 

2.0
2.4
-1.0

Round Numbers in Python using Numpy Module

NumPy module in Python provides the numpy.round() function to round numbers. This function rounds each element of an array to the nearest integer or to the specified number of decimals.

Example :In this example the below code uses the NumPy module to create an array `arr` and rounds each element to the nearest integer (`rounded_integers`) and to two decimal places (`rounded_decimals`). The results are then printed for display.

Python3




import numpy as np
 
# Creating an array
arr = np.array([1.234, 2.567, 3.789])
 
# Rounding each element to the nearest integer
rounded_integers = np.round(arr)
 
# Rounding each element to two decimal places
rounded_decimals = np.round(arr, decimals=2)
 
# Displaying the results
print("Nearest integer:", rounded_integers)
print("Decimal places:", rounded_decimals)


Output :

Nearest integer: [1. 3. 4.]
Decimal places: [1.23 2.57 3.79]

Round Numbers in Python using Rounding Bias concept.

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, as the value is always rounded up in the direction of positive infinity. Similarly, the rounding down strategy has a round towards negative infinity bias. The truncation strategy has 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. 

a) Rounding Half Up concept in Python

The rounding half-up rounds every number to the nearest number with the specified precision and breaks ties by rounding up. 
The rounding half-up strategy is implemented by shifting the decimal point to the right by the desired number of places. In this case, we will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5. 
We can add 0.5 to the value which is shifted and then round it down with the math.floor() function. 

Implementation of round_half_up() function: 

Example: In this example the below code defines `round_half_up`, a custom rounding function using the “round half up” method with `math.floor()` for precision. Demonstrations include positive and negative numbers with various decimal places.

python3




import math
 
# defining round_half_up
 
def round_half_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier + 0.5) / multiplier
 
# passing different values to the function
 
print(round_half_up(1.28, 1))
print(round_half_up(-1.5))
print(round_half_up(-1.225, 2))


Output: 

1.3
-1.0
-1.23

b) Rounding Half Down concept in Python

This rounds to the nearest number similar to the rounding half-up method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Rounding half down strategy is implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding. 

Implementation of round_half_down() function: 

In this example the below code defines `round_half_down` using the `math` library to achieve round-half-down behavior. It utilizes multiplication, subtraction, and `math.ceil()` for rounding towards zero. Test cases include positive and negative decimals, rounding to one decimal place.

python3




# import math library
import math
 
# defining a function
# for round_half_down
def round_half_down(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier - 0.5) / multiplier
 
# passing different values to the function
print(round_half_down(2.5))
print(round_half_down(-2.5))
print(round_half_down(2.25, 1))


Output: 

2.0
-3.0
2.2

Rounding Half Away From Zero in Python

In Rounding Half Away From Zero we need to do is to start as usual by shifting the decimal point to the right a given number of places and then notice the digit(d) immediately to the right of the decimal place in the new number. There are four cases to consider:

  • If n is positive and d >= 5, round up
  • If n is positive and d = 5, round down
  • If n is negative and d >= 5, round down
  • If n is negative and d < 5, round up

After rounding as per the rules mentioned above, we can shift the decimal place back to the left. 

  • Rounding Half To Even: There is a way to mitigate rounding bias while we are rounding values in a dataset. We can simply round ties to the nearest even number at the desired precision. The rounding half to even strategy is the strategy used by Python’s built-in round(). The decimal class provides support for fast correctly-rounded decimal floating-point arithmetic. This offers several advantages over the float datatype. The default rounding strategy in the decimal module is ROUND_HALF_EVEN.

Example: In this example the below code uses the `Decimal` function from the `decimal` library to represent decimal numbers precisely. It contrasts creating a `Decimal` object from a string and directly from a floating-point number. The `quantize()` function is then employed for rounding with specified decimal places, demonstrating precision in decimal arithmetic.

python3




# import Decimal function from
# decimal library
from decimal import Decimal
print(Decimal("0.1"))
print(Decimal(0.1))
 
# Rounding a Decimal number is
# done with the .quantize() function
# "1.0" in .quantize() determines the
# number of decimal places to round the number
print(Decimal("1.65").quantize(Decimal("1.0")))
print(Decimal("1.675").quantize(Decimal("1.00")))


Output: 

0.1
0.1000000000000000055511151231257827021181583404541015625
1.6
1.68


Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads