How to Round a Floating Point Number in Python?

It is important to round a floating-point number in order to make it readable. By default, python would return a floating-point number with 16 decimal points when you do divide operations. So, we have to round it as per our use case. Here, I shared 3 simple methods to round a floating number in python.

1. Using Built-in Round Method

It is the easiest method. The round() method takes two arguments. The first one is the float you want to round off. The second argument is used to limit the number of decimal points and it is optional. If you don’t supply the second argument, the floating-point number will be converted into a whole number.

Example 1:

number = 5.33
rounded_number = round(number)
print(rounded_number) # 5

Example 2:

number = 5.3333333334
rounded_number = round(number, 2)
print(rounded_number) # 5.33

2. F-String Method

It is a string formatting mechanism. This method works faster than all other string formatting methods.

number = 5.3333333334
rounded_number = f'{number:.2f}'
print(rounded_number) # 5.33

3. Format Method

We can also use the built-in format() method to round a lengthy floating-point number. It works similarly to the 2nd method.

number = 5.3333333334
rounded_number = format(number, '.2f')
print(rounded_number) # 5.33

Recommended Method

The first method is the latest method. It works very fast for rounding any float in python.