Python float()

The float() method returns a floating point number from a number or a string.

Example


float() Syntax

The syntax for float() is:

float([x])

float() Parameters

The float() method takes a single parameter:

  • x (Optional) - number or string that needs to be converted to floating point number
    If it's a string, the string should contain decimal points
Parameter Type Usage
Float number Use as a floating number
Integer Use as an integer
String Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of "+", "-" signs. Could contain NaN, Infinity, inf (lowercase or uppercase).

float() Return Value

The float() method returns:

  • Equivalent floating point number if an argument is passed
  • 0.0 if no arguments passed
  • OverflowError exception if the argument is outside the range of Python float

Example 1: How float() works in Python?

Output

10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

Example 2: float() for infinity and Nan(Not a number)?

Output

nan
nan
inf
inf
inf
inf