AttributeError: 'float' object has no attribute 'round'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'float' object has no attribute 'round' #

The Python "AttributeError: 'float' object has no attribute 'round'" occurs when we try to call the round function on a float number. To solve the error, pass the float as an argument to the round() function, e.g. round(3.6).

attributeerror float object has no attribute round

Here is an example of how the error occurs.

main.py
example = 3.6 # ⛔️ AttributeError: 'float' object has no attribute 'round' result = example.round() print(result)

To solve the error, we have to pass the float as an argument to the round function, not call the function on the float.

main.py
fav_num = 3.456 result1 = round(fav_num) print(result1) # 👉️ 3 result2 = round(fav_num, 2) print(result2) # 👉️ 3.46

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal the number should have after the operation (optional)

The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

Instead of accessing the round() function on the float, e.g.my_float.round(), we have to pass the floating point number as an argument to the round() function, e.g. round(3.5).

A good way to start debugging is to print(dir(your_object)) and see what attributes the object has.

Here is an example of what printing the attributes of a float looks like.

main.py
example = 3.45 # [..., 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real', ...] print(dir(example))

If you pass a class to the dir() function, it returns a list of names of the class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: float object has no attribute" error.

Since round is not present in the list of attributes, trying to access it causes the error.

Conclusion #

The Python "AttributeError: 'float' object has no attribute 'round'" occurs when we try to call the round function on a float number. To solve the error, pass the float as an argument to the round() function, e.g. round(3.6).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.