Home Python How to Round in Python (with examples)

How to Round in Python (with examples)

Round() is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places given as input. If the decimal places to be rounded are not specified, it is considered 0, and it will round to the nearest integer.

Syntax:

round(float_number, number_of_decimals)
• float_number is the float number to be rounded.
• number_of_decimals is the number of decimals while rounding. The number is optional, and the number defaults to 0 if the number is not specified. When the second argument is present, it will round to the number of places given, and the return type will be a float number.

Considerations for the number of decimals if given.

• >=5 than + 1 will be added to the final value

• <5 then the final value will return as it is up to the decimal places mentioned.

Return value

It will return an integer value if the number_of_decimals is not given and a float value if the number_of_decimals is given.

The value will be rounded to +1 if the value after the decimal point is >=5; else, it will return the value as it is up to the decimal places given.

Rounding vs. Truncation

The Impact of Rounding: Vancouver Stock Exchange 1982.

Vancouver Stock Exchange used to truncate stock values to three decimal places on each trade. Truncation was done almost 3000 times every day. The accumulated truncations led to a loss of around 25 points per month.

Example: Truncating vs. Rounding

Consider the floating-point numbers (0.02 and 0.07) as stock values. Let’s generate floating-point numbers for a range of 1000000 seconds between the values (0.02 and 0.07).

arr = [random.uniform(0.02, 0.07) for _ in range(1000000)]

To illustrate truncating numbers’ impact, we will truncate the numbers after three decimal places. We will have the original total value, total coming from truncated values and the difference between original and truncated values.

We will also use the round() method using the same set of values to calculate up to three decimal places to calculate the sum and difference of the original value and the rounded value.

Example A:

import random

def truncate(num):
return int(num * 1000) / 1000

arr = [random.uniform(0.02, 0.07) for _ in range(1000000)]
sum_num = 0
sum_truncate = 0
for i in arr:
  sum_num = sum_num + i
  sum_truncate = truncate(sum_truncate + i)


print("Testing by using truncating upto 3 decimal places")
print("The original sum is = ", sum_num)
print("The total using truncate = ", sum_truncate)
print("The difference from original - truncate = ", sum_num - sum_truncate)

print("\n\n")
print("Testing by using round() upto 3 decimal places")
sum_num1 = 0
sum_truncate1 = 0
for i in arr:
  sum_num1 = sum_num1 + i
  sum_truncate1 = round(sum_truncate1 + i, 3)


print("The original sum is =", sum_num1)
print("The total using round = ", sum_truncate1)
print("The difference from original - round =", sum_num1 - sum_truncate1)

Output:

Testing by using truncating up to 3 decimal places
The original sum is = 44989.67031639265
The total using truncate = 44489.863
The difference from original - truncate = 499.80731639265287

Testing by using round() up to 3 decimal places
The original sum is = 44989.67031639265
The total using round = 44989.782
The difference from original - round = -0.11168360734882299

From the example above, the difference between the original and truncated value is 499.80731639265287.

The difference between the original value and from rounding it is -0.11168360734882299. The difference between the two examples is huge.

This example indicates how the round() method helps calculate values close to accuracy.

Rounding Float Numbers

round() on float numbers

float_number1 = 20.70 # the value will be rounded to 21 as after the decimal point the number is 7 that is >5
float_number2 = 20.40 # the value will be rounded to 20 as after the decimal point the number is 4 that is <=5
float_number3 = 30.3468 # the value will be 30.35 as after the 2 decimal points the value >=5
float_number4 = 10.3439 # the value will be 10.34 as after the 2 decimal points the value is <5

print("The rounded value without num_of_decimals is :", round(float_number1))
print("The rounded value without num_of_decimals is :", round(float_number2))
print("The rounded value with num_of_decimals as 2 is :", round(float_number3, 2))
print("The rounded value with num_of_decimals as 2 is :", round(float_number4, 2))

Output:

The rounded value without num_of_decimals is: 21
The rounded value without num_of_decimals is: 20
The rounded value with num_of_decimals as 2 is: 30.35
The rounded value with num_of_decimals as 2 is: 10.34

Rounding Integer Values

Using the round() method on an integer will return the number without making any changes to the value.

testing round() on an integer

num = 45

print("The output is", round(num))

Output:

The output is 45

Rounding on Negative Numbers

The example below demonstrates what happens when round() is applied on negative integers.

testing negative numbers round()

number1 = -12.8
number2 = -41.5

print("The value after rounding is", round(number1))
print("The value after rounding is", round(number2))

Output:

The value after rounding is -13
The value after rounding is -42

Round Numpy Arrays

To round arrays in Python, we use the NumPy module, NumPy.round(), or NumPy.around() methods to find the rounded values.

Using numpy.round()

testing numpy.round() on Arrays

import NumPy as np

arr = [-0.541331, 3.4555648989, 14.7652323, -0.94893326, 88.1111632, 35.122323]

arr1 = np.round(arr, 2)

print(arr1)

Output:

[ -0.54 3.46 14.77 -0.95 88.11 35.12]

Using numpy.around()

testing numpy.around()

import NumPy as np

arr = [-0.541331, 3.4555648989, 14.7652323, -0.94893326, 88.1111632, 35.122323]
arr1 = np.around(arr, 2)
print(arr1)

Output:

[ -0.54 3.46 14.77 -0.95 88.11 35.12]

Rounding arrays using either numpy.round() method or numpy.around() method give the same result.

Python’s Decimal Module

Python also has a decimal module used to handle decimal numbers more accurately than the round modules. The following are the different rounding types in the decimal module.

ROUND_CEILING rounds values towards infinity. ​

ROUND_FLOOR will round a number towards – infinity. ​

ROUND_UP will round a value to where the value will go away from zero. ​

ROUND_DOWN will round the given number towards zero. ​

ROUND_HALF_UP will round a number to the nearest, with the value going away from zero. ​

ROUND_HALF_DOWN will round a number to the nearest value going towards zero. ​

ROUND_HALF_EVEN will round a number to the nearest with the value going to the nearest even integer.

To demonstrate the decimal module in Python, we will use the quantize() method, which is used to round a number to a fixed number of decimal places. To use it, you have to specify the rounding to be used.

Using the round() and the decimal methods

import decimal
round_number = 66.456

final_value = round(round_number, 2)

Using decimal module

final_value1 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_CEILING)
final_value2 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_DOWN)
final_value3 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_FLOOR)
final_value4 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_DOWN)
final_value5 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_EVEN)
final_value6 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
final_value7 = decimal.Decimal(round_number).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)


print("Using round()", final_value)
print("Using Decimal - ROUND_CEILING ",final_value1)
print("Using Decimal - ROUND_DOWN ",final_value2)
print("Using Decimal - ROUND_HALF_UP ",final_value6)
print("Using Decimal - ROUND_FLOOR ",final_value3)
print("Using Decimal - ROUND_HALF_DOWN ",final_value4)
print("Using Decimal - ROUND_HALF_EVEN ",final_value5)
print("Using Decimal - ROUND_UP ",final_value7)

Output:

('Using round()', 66.46)
('Using Decimal - ROUND_CEILING ', Decimal('66.46'))
('Using Decimal - ROUND_DOWN ', Decimal('66.45'))
('Using Decimal - ROUND_HALF_UP ', Decimal('66.46'))
('Using Decimal - ROUND_FLOOR ', Decimal('66.45'))
('Using Decimal - ROUND_HALF_DOWN ', Decimal('66.46'))
('Using Decimal - ROUND_HALF_EVEN ', Decimal('66.46'))
('Using Decimal - ROUND_UP ', Decimal('66.46'))

Errors and Exceptions

Type Error is raised when a value other than a number is used as a parameter in the round() method.

print(round("a", 2))
>>> print(round("a", 2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type str doesn't define __round__ method

Practical Applications

The practical use of rounding functions in Python is handling the mismatch that is always witnessed between decimals and fractions. Rounding numbers are used to shorten all the three’s to the decimal point’s right to convert 1/3 to decimal. The rounded numbers 0.33 or 0.333 are used when you need to work with 1/3 in decimal. It is practical to work with two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal.

b = 1/3
print(b)
print(round(b, 2))

Output:

0.3333333333333333
0.33

Recap

In this article, we looked deeply at round in Python. We have illustrated various dynamic and versatile examples that will hopefully drive the point home. If you did not master anything in this rundown, please re-examine it again. But the key takeaways include the following:

  • Round(a,b) is a built-in function in Python which returns a float number that will be rounded to the decimal places given as input to the method.
  • In the example round(a,b): a is the float number to be rounded.
  • In the example round(a,b): b is the number of decimals used in rounding.
  • Round() will return an integer value if the number of decimals (b) is not given and a float value if (b) is provided.
  • Every rounding strategy in Python inherently introduces a rounding bias which can be mitigated most of the time using the rounding half to even strategy.
  • Storage of floating-point numbers in memory by computers introduces a subtle rounding error which we can work around using the decimal module in Python.
  • You can also round Numpy Arrays, Pandas Series, and DataFrame objects.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More