Python float() Function: Syntax and 6 Examples

If you want a decimal number in Python, the Python float function does exactly that. It takes "19.99" or 7 and gives you back a float for decimal math.

print(float("19.99") + float(7))
# 26.99

In this tutorial, I’ll show you float() in six real examples: strings, inf and NaN, order totals, integers, safe conversion and custom objects. I ran each one in Python 3.12.5 with VS Code.

Python float() Syntax

float(number=0.0, /)
float(string, /)
ParameterRequiredDefaultDescription
numberNo0.0An int, float, bool or number-like object
stringNononeText holding a decimal number, inf or nan

Return value: a new float, or 0.0 with no argument. Invalid text raises ValueError, and numbers too big for a float raise OverflowError.

Note: Python 3.14 added float.from_number(), a stricter cousin that refuses strings. For more string cases, see how to convert a string to a float in Python.

When to Use float() in Python

  • Reading prices you type, which arrive as strings
  • Converting CSV or Excel amounts before adding them
  • Turning an integer into a float for decimal math
  • Creating infinity or NaN as a starting value

You’ll often pair it with the Python input() function.

Example 1: Convert a String to a Float with float()

Let me start with strings, the most common job:

print(float("19.99"))
print(float("  -12.5\n"))
print(float("+1E3"))
print(float("1_000.75"))
print(float(42))
print(float())

Output:

19.99
-12.5
1000.0
1000.75
42.0
0.0
Python float function converting strings with spaces, signs, exponents and underscores in VS Code
Spaces, signs and exponents work.

How does this work? float() stripped the spaces around -12.5, read +1E3 as 1000.0 and dropped the underscore. No argument gives 0.0.

Not sure what the text holds? See checking if a string is an integer or float.

Example 2: Can Python float() Create Infinity and NaN?

Yes. Python’s float() reads special words and scientific notation too:

import math

for text in ["inf", "-Infinity", "NaN", "2.5e-3"]:
    value = float(text)
    print(text, "->", value, math.isinf(value), math.isnan(value))

Output:

inf -> inf True False
-Infinity -> -inf True False
NaN -> nan False True
2.5e-3 -> 0.0025 False False
Python float converting inf, -Infinity, NaN and scientific notation with math.isinf and math.isnan
inf and NaN are real floats.

How does this work? "NaN" became nan, so math.isnan() returned True. "2.5e-3" is 0.0025, and neither check flagged it.

Pro Tip: NaN never equals itself, so check for NaN with math.isnan(). More on scientific notation strings.

Example 3: Total USD Order Amounts from CSV Text in Python

CSV data arrives as text. Here you’ll total three orders from US cities:

rows = ["Austin,19.99", "Denver,7.50", "Boston,124.35"]

total = 0.0
for row in rows:
    city, amount = row.split(",")
    total += float(amount)

print(f"Order total: ${total:,.2f}")

Output:

Order total: $151.84
Python float converting CSV order amounts to a USD total with an f-string
Amounts added and formatted in USD.

How does this work? float(amount) made each amount addable, and :,.2f printed $151.84.

See rounding to 2 decimal places and formatting numbers as currency in Python.

Example 4: Convert Integers and Booleans to float

Integers convert cleanly, but you’ll hit precision limits:

print(float(7), float(True), float(-3))
print(0.1 + 0.2)
print(float(2**53) == float(2**53 + 1))

Output:

7.0 1.0 -3.0
0.30000000000000004
True

How does this work? True became 1.0. 0.1 + 0.2 printed 0.30000000000000004, and two different integers above 2**53 became the same float.

Read how floating point numbers work in Python, or go back with float to int conversion.

Example 5: Fix ValueError with float() and try/except

Your input will have dollar signs, commas and blanks. This helper cleans them:

def to_float(value, default=0.0):
    try:
        return float(str(value).replace("$", "").replace(",", ""))
    except ValueError:
        return default

for value in ["$1,249.99", "N/A", "", None]:
    print(repr(value), "->", to_float(value))

Output:

'$1,249.99' -> 1249.99
'N/A' -> 0.0
'' -> 0.0
None -> 0.0
Python float wrapped in try except stripping dollar signs and commas, returning 0.0 for bad input
Bad values return 0.0.

How does this work? "$1,249.99" became 1249.99. The other three raised ValueError (None became the text “None”) and returned 0.0.

Related: fixing could not convert string to float and catching multiple exceptions.

Example 6: Use float() on Decimal, Fraction and Custom Objects

Any object with a __float__() method works with float():

from decimal import Decimal
from fractions import Fraction

class Temperature:
    def __init__(self, f):
        self.f = f
    def __float__(self):
        return (self.f - 32) * 5 / 9

print(float(Decimal("19.99")), float(Fraction(1, 4)))
print(float(Temperature(212)))

Output:

19.99 0.25
100.0

How does this work? Decimal, Fraction and Temperature all define __float__(), so 212°F came back as 100.0.

Also see the Python complex() function.

Common Mistakes with Python float()

Here are the Python float() errors I see most (eval() just runs each string):

tests = ['float("1,250.00")', 'float("$19.99")', 'float(None)',
         'float(10**400)', 'float([2.5])']

for n, expr in enumerate(tests, 1):
    try:
        eval(expr)
    except Exception as err:
        print(f"{n}. {type(err).__name__}: {err}")

Output:

1. ValueError: could not convert string to float: '1,250.00'
2. ValueError: could not convert string to float: '$19.99'
3. TypeError: float() argument must be a string or a real number, not 'NoneType'
4. OverflowError: int too large to convert to float
5. TypeError: float() argument must be a string or a real number, not 'list'
Common Python float errors: commas, dollar signs, None, overflow and a list
Five float() errors.

Strip commas and symbols first, check for None, and convert list items one at a time.

For display, format a number with commas after converting.

Wrapping Up the Python float() Function

Python’s float() function turns strings, integers and number-like objects into floats. Clean symbols first and use try/except for bad input. In pandas, astype(float) converts a column.

Next, browse more Python built-in functions and methods.

Want to practice more number conversions? Pick one of these:

Python float() Function FAQs

Does float() round numbers in Python?

No. It keeps the value as closely as a 64-bit float can. Use round() to round.

What does float(input()) do?

It reads a typed line and converts it. Text like “abc” raises ValueError.

Should I use float or Decimal for money?

Use Decimal when cents must be exact. A float is fine for display.

Where can I read the full float() reference?

The string grammar and version notes are in float() in the Python docs.