Python float()

Summary: in this tutorial, you’ll learn how to use Python float() to convert a number or a string to a floating point number.

Introduction to the Python float() #

The float() accepts a string or an number, either an integer or a floating-point number, and converts it to a floating-point number, if possible:

float(x)Code language: Python (python)

If x is a string, it should contain a decimal number. Also, it can have an optional sign like a minus (-) or plus (+).

If x is an integer or a floating point number, the float() returns the same floating point number with the same value. If the value is outside the range of a Python float, the float() will raise an OverflowError.

If x is an object, the float() delegates to the x.__float__() method. If the object x does not have the __float__() method, the float() will use the __index__() method.

The x parameter is optional. If you omit it, the float() will return 0.0.

Python float() examples #

Let’s take some examples of using the Python float().