Skip to main content

Python float() Function

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

Syntax

float(x)

float() Parameters

Python float() function parameters:

ParameterConditionDescription
xOptionalA number or a string that can be converted into a floating point number
note

If x is a String,

  • It 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

Python float() function 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

Examples

Example 1: basic example of float() function

int_number = 123

# convert int to float
float_number = float(int_number)
print(float_number) # Output: 123.0

output

123.0

Example 2: common cases of float() function

# for integers
print(float(10))

# for floats
print(float(12.34))

# for string floats
print(float("-12.34"))

# for string floats with whitespaces
print(float(" -12.34\n"))

# string float error
print(float("abc"))

output

10.0
12.34
-12.34
-12.34
Traceback (most recent call last):
File "main.py", line 14, in <module>
print(float("abc"))
ValueError: could not convert string to float: 'abc'
note

Notice that float("abc") raises a ValueError because abc can not be converted to float number!

Example 3: float() function for infinity and NaN (Not a Number)

# for NaN
print(float("nan"))
print(float("NaN"))

# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

output

nan
nan
inf
inf
inf
inf