Skip to content

Python float() Function

How to convert integers, strings, and special values like 'inf' or 'NaN' to floating-point numbers in Python using the built-in 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:

Parameter Condition Description
x Optional A number or a string that can be converted into a floating point number

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

float_number = float(int_number)
print(float_number)     # Output: 123.0

output

123.0

Example 2: common cases of float() function

print(float(10))

print(float(12.34))

print(float("-12.34"))

print(float("     -12.34\n"))

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'

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

print(float("nan"))
print(float("NaN"))

print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

output

nan
nan
inf
inf
inf
inf
Navigation