Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Convert a String to Float in Python (Commas and Errors)

Convert Python numeric strings with float(), handle comma and locale formats safely, and catch ValueError and OverflowError.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in float(text) for text written in Python’s numeric format. If the text includes thousands separators or locale-specific punctuation, normalize it only when the source format is known, or use locale.atof() for the active locale. Catch ValueError for invalid text and OverflowError for values outside the supported float range.

Convert an ordinary numeric string with float()

For a string in Python’s float format, pass it directly to float():

value = float("  -12.5e2  ")
print(value)  # -1250.0

Python documents float() as returning “a floating-point number constructed from a number or a string.” Its accepted string syntax includes leading and trailing whitespace, optional signs, decimal points, exponents, inf or infinity, nan, and underscores between digits. See the Python 3.14.7 built-in functions reference for the full grammar.

Convert strings that contain commas

A comma thousands separator is not part of the documented float() string grammar. A string such as "1,234.56" therefore needs handling before conversion.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Known format: comma groups thousands, period marks decimals

If the source explicitly uses commas for grouping and periods for decimal marks, remove only the grouping commas:

text = "1,234.56"
value = float(text.replace(",", ""))  # 1234.56

This is safe only when that convention is established. Do not remove commas indiscriminately: in another format, a comma may be the decimal mark, and removing it would change the value.

Locale-formatted input

For text that follows the runtime’s active LC_NUMERIC convention, use locale.atof():

import locale

# Configure the intended LC_NUMERIC locale for the application first.
value = locale.atof("1.234,56")

The punctuation accepted depends on the active locale; the example is not guaranteed to work unchanged on every machine. Python’s locale documentation explains that atof() delocalizes the string using locale conventions before converting it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the conversion method for your input

Method Use it when Trade-off
float(text) The input uses Python-style decimal or exponent notation. Simple and locale-independent; grouping commas are not accepted by the documented grammar.
Normalize, then float() The source uses a fixed, explicitly specified number format. Works when the normalization matches the source; guessing at ambiguous separators can change the value.
locale.atof(text) The input follows the active LC_NUMERIC convention. Locale-aware, but dependent on process locale configuration.

Handle invalid or out-of-range input

Invalid numeric text raises ValueError. A value outside the range of a Python float can raise OverflowError. Handle these as input-validation failures rather than silently substituting a number:

try:
    value = float(user_text)
except ValueError:
    # Report or reject text that is not a valid float representation.
    ...
except OverflowError:
    # Report a value outside the range of a Python float.
    ...

Successful conversion does not always mean the result is an ordinary finite measurement: float() accepts nan and infinity spellings. If your application requires a finite result, check that condition after conversion.

Do not use eval() to parse numeric input

Avoid eval() for converting user-provided text. Python’s programming FAQ warns against using it for this purpose because evaluating input can be unsafe. Use float() or a format-aware parsing approach instead.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When a float is not the right representation

Binary floating-point is appropriate for many calculations, but it does not guarantee exact decimal arithmetic. If the application needs exact decimal behavior, such as for money, investigate decimal.Decimal and its input and arithmetic rules rather than assuming that successful conversion to float preserves every decimal value exactly.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.