Python float() Function

Python’s built-in float(value) function converts the argument value to a float number. For example, float('42') converts the string value '42' into the float number 42.0.

Python float()

ArgumentvalueA Python object to be converted into a float number. The value object must have an __float__() method that returns the associated float number—otherwise a ValueError will be raised.
Return ValuefloatReturns a float number after converting the input argument value using its required __float__() method for the conversion.
>>> float('42')
42.0
>>> float('-42')
-42.0
>>> float('+1.42')
1.42
>>> float('   -11\n')
-11.0
>>> float('10e-3')
0.01
>>> float('+1E6')
1000000.0

Python float() Video


Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

Python float() Custom Object

To allow a custom object as an input to the float(object) function, the object must implement the __float__(self) dunder method that returns a float value. In fact, the float(object) built-in function is semantically equivalent to the object.__float__() function call.

class Car:
    def __float__(self):
        return -3.21


porsche = Car()
print(float(porsche))
# -3.21

In the example, you create a class Car and implement the __init__(self) method that always returns the float (e.g., -3.21). Thus, you can pass a Car object porsche into the float() function and Python doesn’t throw an exception.

Speaking of which…

Python float() Exception

If you pass an object into the float() function that doesn’t implement the __float__() method—for example, a list, tuple, or set—Python throws a TypeError:

class Car:
    None


porsche = Car()
print(float(porsche))

This leads to the error message:

Traceback (most recent call last):
  File "C:\Users\finxter\...\code.py", line 6, in <module>
    print(float(porsche))
TypeError: float() argument must be a string or a number, not 'Car'

To fix the error, either pass an object that is convertible to an integer or implement your own __int__(self) method as shown previously:

class Car:
    def __float__(self):
        return 42.42


porsche = Car()
print(float(porsche))
# 42.42

Note that the same TypeError appears if you try to convert lists, sets, dictionaries, or tuples to integer values using the float() function.

Lists:

>>> float([1, 2, 3])
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    float([1, 2, 3])
TypeError: float() argument must be a string or a number, not 'list'

Sets:

>>> float({1, 2, 3})
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    float({1, 2, 3})
TypeError: float() argument must be a string or a number, not 'set'

Dictionaries:

>>> float({'Alice': 23, 'Bob': 17})
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    float({'Alice': 23, 'Bob': 17})
TypeError: float() argument must be a string or a number, not 'dict'

Tuples:

>>> float((1, 2, 3))
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    float((1, 2, 3))
TypeError: float() argument must be a string or a number, not 'tuple'

Summary

Python’s built-in float(value) function converts the argument value to a float number.

For example, float('42') converts the string value '42' into the float number 42.0.

>>> float('42')
42.0

Want to keep improving your Python skills? Check out our free Python cheat sheets:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!