Wed Apr 20 2022·2 min read
Photo by Alice Donovan Rouse
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.
Here is an example of how the error occurs.
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.
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:
|the number to round to |
|the number of digits after the decimal the number should have after the operation (optional)|
round function returns the number rounded to
ndigits precision after the
ndigits is omitted, the function returns the nearest integer.
round()function on the float, e.g.
my_float.round(), we have to pass the floating point number as an argument to the
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.
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 classes' attributes, and recursively of the attributes of its bases.
round is not present in the list of attributes, trying to access it
causes the error.