English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico do Python

Controle de fluxo no Python

Função do Python

Tipos de Dados do Python

Operações de arquivos no Python

Objetos e classes no Python

Data e hora no Python

Conhecimentos avançados do Python

Manual de referência do Python

Métodos e exemplos de uso do float() no Python

Python built-in functions

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

The syntax of float() is:

float([x])

float() parameter

float() method takes one parameter:

  • x (optional)  -The number or string that needs to be converted to a floating-point number.
    If it is a string, then the string should contain a decimal point

Different parameters of float()
Parameter typeUsage
Float numberUsed as a floating-point number
IntegerUsed as an integer
String Must contain decimal numbers.
Leading and trailing spaces are removed.
Optional use of “ +”,“-” symbol.
Can include NaN, Infinity, inf (either uppercase or lowercase).

float() return value

float() method returns:

  • Equivalent floating-point number when passing parameters

  • If no parameter is passed, it is 0.0

  • If the parameter is out of the range of Python float, an OverflowError exception will occur

Example1:How does float() work in Python?

# Parameter is an integer
print(float(10))
# Parameter is a floating point
print(float(11.22))
# Parameter is a string float
print(float("-13.33"))
# Parameter is a string with spaces
print(float("     -24.45\n"))
# Parameter is a string, will throw a floating-point error
print(float("abc"))

When running the program, the output is:

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

Example2:Does float() handle infinity and Nan (not a number)?

# Parameter is NaN
print(float("nan"))
print(float("NaN"))
# Parameter is inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

When running the program, the output is:

nan
nan
inf
inf
inf
inf

Python built-in functions