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


But before we move on, I’m excited to present you my brand-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).

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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!