How to round a number or float list in Python?

Rounding float numbers in Python

To handle rounding of floats, we use the built-in round() function or the decimal module. In case that we have an iterable such as a list or dictionary we can use a comprehension to round the iterable elements.

``````
float_lst = [12.3344, 15.343, 45.556665, 7.33]

# round elements using list comprehension
rounded_lst = [ round(e,1) for e in float_lst]

# print list
print(rounded_lst)``````

Let’s look at more examples:

Example 1:

As we learned, Python has an inbuilt function round(), which will take the float value and round it off. The function takes two parameters: Number and Ndigits (optional). Ndigits represent the number of decimal places to round. In the example below, we have rounded off the value to 2 (round(float(i), 2), so the result value would be rounded off with 2 digits after the decimal.

Code:

``````def getroundvalue(i):
return round(float(i),2)
uservalue = input("Enter a float number:")
print(getroundvalue(uservalue))``````

Output:

``````Enter a float number:3.7890
Round number of the provided value: 3.79``````

Example 2: Round float numbers in Python list

To round the values in a list, we will assign an empty list variable. Then, we use the For loop to iterate and apply the round() function for each float value to obtain the list of rounded values.

Code:

``````def getroundvalues(listfloatvalues):
for i in listfloatvalues:
value.append(round(i))
return value
list = [2.7,4.2,8.9,1.5]
value = []
print("List of Float numbers:", list)
print("Round number from the list:",getroundvalues(list))``````

Output:

``````List of Float numbers: [2.7, 4.2, 8.9, 1.5]
Round number from the list: [3, 4, 9, 2]``````

Example 3: Using Decimal Module

The decimal module in Python helps us to increase the accuracy of the floating-point number. We need to import decimal to utilize it.

Code:

``````import decimal
floatnumber = 4.5662
value = decimal.Decimal(floatnumber)
getroundvalue = value.quantize(decimal.Decimal('0.00'))
print("Float value:", floatnumber)
print("Round value:", getroundvalue)``````

Output:

``````Float value: 4.5662
Round value: 4.57``````

Note:

• Using decimal.Decimal(floatnumber) would provide a decimal value of 50 digits as default.
• Hence we use value.quantize(decimal.Decimal(‘0.00’)) to only provide 2 digits after the decimal.

Rounding a Numpy Array

The python Numpy library also delivers functionality to round an array. Here’s a simple example:

``````import numpy as np
float_lst = [12.3344, 15.343, 45.556665, 7.33]

# create array from list
my_array = np.array(float_lst)

my_array.round(decimals=1)

# output will be : array([12.3, 15.3, 45.6,  7.3])``````