How to round up a float number in Python?

Problem:

Today, we’ll learn how to round up float numbers using Python.

Solution:

We have two methods to handle the rounding float numbers in Python. Using the round() function and Decimal module. We will look at the solutions with examples for each method in this post.

Option 1: Python Round Function

Python has an inbuilt function round(), which will take the float value and round it off. The round() 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

Practical Example: Round float numbers in a 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]

Option2: 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.