Python / float() / Convert Values to Floating-Point Numbers

Python’s float() converts numbers and supported numeric strings to floating-point numbers. With no argument it returns 0.0, but it does not automatically turn an empty string or None into zero. Successful conversion alone does not guarantee a finite value or the decimal precision your task requires.

Basic conversion and the original value

float(value) returns a result without changing the original variable’s type. Floating point represents quantities using a finite number of bits and may approximate fractional values. A visible decimal point is not a reliable test of type or accuracy. See the official float() reference for accepted inputs.

The complete examples use Python 3 and the standard library. Save the program as UTF-8 in float_example.py and run python float_example.py, or python3 where appropriate. Later examples can each replace the file contents and run independently.

value = 3
converted = float(value)
print(converted, type(converted).__name__)
print(value, type(value).__name__)
print(float("  -2.5  "))
print(float("1e3"))
print(float())
print(float(True))

Expected output:

3.0 float
3 int
-2.5
1000.0
0.0
1.0

The original value remains an integer. Strings may contain surrounding whitespace, a sign, or exponent notation such as 1e3. True becomes 1.0, so explicitly reject Boolean input if your application does not permit it.

Input formats, ValueError, and TypeError

Ordinary numeric strings use . as the decimal separator. Thousands separators, decimal commas, and currency symbols are not interpreted automatically. A malformed numeric string raises ValueError; an unsupported object such as None raises TypeError.

for value in ("1,234.5", "2,5", "", None):
    try:
        print(float(value))
    except (ValueError, TypeError) as error:
        print(type(error).__name__)
ValueError
ValueError
ValueError
TypeError

Blindly deleting commas can turn an intended decimal 2,5 into 25. Define the input format and locale rules first, then normalize only under those known rules. Decide whether empty input is an error or missing data instead of silently merging it with a real zero.

Why 0.1 plus 0.2 may not equal 0.3

On most systems, floats use binary floating-point storage. Some decimal fractions cannot be represented by a finite binary fraction and are stored approximately. This is a representation limit rather than a failed conversion. The Python floating-point tutorial explains the mechanism.

import math
from decimal import Decimal

result = 0.1 + 0.2
print(result)
print(result == 0.3)
print(math.isclose(result, 0.3))
print(Decimal("0.1") + Decimal("0.2"))
0.30000000000000004
False
True
0.3

math.isclose() supports approximate comparison, but tolerances must fit your units and accuracy requirements; consider abs_tol near zero. For exact decimal requirements, consider Decimal initialized from the original decimal string. Decimal(0.1) starts from an already approximated binary value and is not the same starting point.

Check NaN, infinity, and overflow

float() accepts nan and inf. NaN means Not a Number, while inf represents infinity. A successful parse therefore need not be a valid finite measurement. Use math.isfinite() when a finite number is required.

import math

for text in ("nan", "inf", "-inf", "2.5"):
    number = float(text)
    print(text, math.isfinite(number))
nan False
inf False
-inf False
2.5 True

An extremely large exponent string can produce infinity, whereas converting an enormous integer can raise OverflowError. NaN also compares unequal to itself: do not detect it using x == float("nan"). Use math.isnan() if you specifically need a NaN check.

print(float("1e400"))
try:
    print(float(10 ** 400))
except OverflowError:
    print("OverflowError")
print(float("nan") == float("nan"))
inf
OverflowError
False

Build a function that accepts only finite numbers

Combine conversion-error handling with a finiteness check. This function distinguishes malformed input from a non-finite number and returns a float only on success. Its English error strings are example messages that you can adapt to your users.

import math

def finite_number(text):
    try:
        number = float(text)
    except (ValueError, TypeError) as error:
        raise ValueError("not a number") from error
    if not math.isfinite(number):
        raise ValueError("not finite")
    return number

for text in ("2.5", "nan", "abc"):
    try:
        print(finite_number(text))
    except ValueError as error:
        print(error)
2.5
not finite
not a number

The function checks finiteness only. Domain-specific values such as ages, quantities, or ratios may also need lower and upper bounds or an integer check. Do not replace every failure with 0.0, which would hide the distinction between invalid data and a genuine zero.