How to Convert String to Float in Python

What you’ll build or solve

You’ll convert numeric strings like "3.14" or " 10 " into Python floats so you can calculate with them.

When this approach works best

Converting a string to a float works well when you:

  • Parse user input from a form or command line, like "19.99" or "0.5".
  • Clean up data read from a CSV or text file, where numbers arrive as strings.
  • Extract numeric values from APIs that return numbers as strings.

Skip this approach for money or other cases that need exact decimal math. Floats can’t represent many decimal values precisely, so use decimal.Decimal instead.

Prerequisites

  • Python 3 installed
  • You know what a string and a float are

Step-by-step instructions

1) Convert a numeric string with float()

float() is the standard way to convert a string to a float.

value="3.14"
n=float(value)

print(n)
print(type(n))

What to look for: float() ignores leading and trailing whitespace, so " 3.14 " still works.


2) Clean common input before converting

Real-world strings often include extra spaces or separators. Clean the string first, then call float().

Option A: Strip whitespace and remove thousands separators

value=" 1,234.50 "
clean=value.strip().replace(",","")
n=float(clean)

print(n)

Option B: Handle comma decimals (common in some locales)

value="12,5"# comma decimal
clean=value.strip().replace(",",".")
n=float(clean)

print(n)

What to look for: Don’t apply both comma fixes blindly. "1,234.50" uses commas for thousands, while "12,5" uses a comma as a decimal separator.


3) Handle invalid strings safely

If the string isn’t a valid number, float() raises ValueError. Catch it and decide what your program should do.

defto_float(value):
try:
returnfloat(value)
exceptValueError:
returnNone

print(to_float("3.14"))
print(to_float("not a number"))

What to look for: None is a common “failed parse” value, but you can also raise your own error or return a default like 0.0, depending on your use case.


Examples you can copy

Example 1: Convert user input from the command line

raw=input("Enter a number: ")

try:
n=float(raw)
print(f"Double:{n*2}")
exceptValueError:
print("Please enter a valid number.")

Example 2: Convert values from a CSV-like list

rows= ["10.5"," 0.25","3","bad"]

numbers= []
forsinrows:
try:
numbers.append(float(s))
exceptValueError:
pass

print(numbers)

Example 3: Convert values with thousands separators

values= ["1,200.00","50","3,000"]

floats= [float(v.replace(",",""))forvinvalues]
print(floats)

Example 4: Convert a dict of string values

payload= {"height":"172.5","weight":"78.0"}

height=float(payload["height"])
weight=float(payload["weight"])

print(height,weight)

Common mistakes and how to fix them

Mistake 1: Passing a non-numeric string to float()

What you might do:

value="12.5kg"
n=float(value)

Why it breaks: float() only accepts valid numeric strings, so it raises ValueError.

Correct approach: Strip the units first, then convert.

value="12.5kg"
clean=value.replace("kg","")
n=float(clean)

print(n)

Mistake 2: Mixing thousands separators and comma decimals

What you might do:

value="1,234.50"
n=float(value.replace(",","."))

Why it breaks: The string becomes "1.234.50", which isn’t a valid number.

Correct approach: Decide which format you have, then clean the right way.

value="1,234.50"
n=float(value.replace(",",""))

print(n)

Mistake 3: Forgetting to check for empty strings

What you might do:

value=""
n=float(value)

Why it breaks: float() raises ValueError on empty strings or whitespace-only strings.

Correct approach: Check first, then convert.

value=""

ifvalue.strip():
n=float(value)
else:
n=0.0

print(n)

Troubleshooting

If you see ValueError: could not convert string to float, print the string and look for commas, spaces in the middle, or extra characters like % or units.

If " 3.14 " fails, the string may contain non-breaking spaces. Replace them before converting:

s=s.replace("\u00a0"," ")

If you get unexpected results for money, switch to decimal.Decimal.

If your input uses comma decimals, replace the decimal comma with a dot, but only when you know that’s the format.


Quick recap

  • Use float("3.14") to convert a numeric string to a float.
  • Clean the string first for spaces and separators, then convert.
  • Wrap conversion in try/except ValueError for messy input.
  • Choose one comma strategy, thousands separators and comma decimals differ.
  • Check for empty or whitespace-only strings before converting.