float()

Converts a value to a floating-point number.

Returns
A floating-point number.
On this page

Example

#
Python
print(float("3.5"))
print(float(7))
print(float("3,5".replace(",", ".")))
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
Resultsaved result, you can check it
3.5
7.0
3.5
0.30000000000000004
0.3

Definition and usage

#

The float() function creates a floating-point number from a string or an integer. The decimal separator must be a dot, so a string like "3,5" raises an error and has to be converted to "3.5" first.

Floating-point numbers have limited precision, which is why 0.1 + 0.2 gives 0.30000000000000004. That's not a bug in Python, just how computers store decimal fractions.

Special values are created from strings: float("inf") is infinity, and float("nan") is "not a number". For financial calculations, the decimal module is a better choice.

Syntax

#
Syntax
float(x)

Parameters

#
  • x

    a string or number

    The value to convert.

Good practices

#
  • Don't compare floating-point numbers with ==. Use math.isclose(a, b).
  • Store money amounts in cents as an int, or use the Decimal type.

Related entries

#

Spotted a mistake or missing an example? Write to us.