Python
string conversion
double
data types
programming basics

How do I convert a string to a double in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, the usual equivalent of a double-precision number is float. Converting a string is therefore usually just float(text), but real code also has to think about invalid input, formatting noise, and whether binary floating point is appropriate for the domain.

Basic Conversion With float

For clean numeric input, use float directly.

python
value = float("3.14159")
print(value)
print(type(value))

It also handles scientific notation.

python
print(float("1.2e3"))
print(float("-4.5E-2"))

If the string is trusted and uses a normal dot decimal separator, that is all you need.

Handle Invalid Input Explicitly

When strings come from users, files, or APIs, wrap the conversion in try and except.

python
1def parse_float(text: str) -> float:
2    try:
3        return float(text.strip())
4    except ValueError as exc:
5        raise ValueError(f"invalid number: {text!r}") from exc
6
7print(parse_float(" 42.0 "))

That gives the caller a useful error instead of a silent failure.

Clean Formatting Noise First

float does not understand commas, currency symbols, or unit suffixes automatically. If the input is formatted, clean it before conversion.

python
1def parse_currency_like(text: str) -> float:
2    cleaned = text.strip().replace(",", "").replace("$", "")
3    return float(cleaned)
4
5print(parse_currency_like("$1,234.50"))

Be careful with this approach if the input may use locale-specific conventions, because not every comma means “thousands separator.”

Watch for nan and inf

Python accepts some special floating-point strings.

python
1import math
2
3x = float("nan")
4y = float("inf")
5
6print(math.isnan(x))
7print(math.isfinite(y))

These values can move through calculations silently. If your domain requires only finite numbers, validate after parsing.

python
1import math
2
3value = float("nan")
4if not math.isfinite(value):
5    raise ValueError("non-finite values are not allowed")

Use Decimal When Precision Matters

If the question really means “a precise decimal number” rather than “Python float,” then Decimal may be the better tool.

python
1from decimal import Decimal
2
3price = Decimal("19.99")
4tax = Decimal("0.13")
5total = price * (Decimal("1") + tax)
6print(total)

float uses binary floating point, which is excellent for many scientific and engineering tasks but can introduce surprising rounding artifacts in financial calculations.

Converting Many Strings at Once

For batch processing, collect both successful conversions and failures instead of crashing on the first bad value.

python
1raw_values = ["10.5", "bad", " 3.0 ", "-7"]
2converted = []
3errors = []
4
5for idx, raw in enumerate(raw_values):
6    try:
7        converted.append(float(raw.strip()))
8    except ValueError:
9        errors.append((idx, raw))
10
11print("converted:", converted)
12print("errors:", errors)

That pattern is useful in ingestion pipelines where partial success is acceptable and bad rows need review.

Convert Entire Columns With a Policy

In real applications, string-to-float conversion often happens at the boundary of a CSV import, API payload, or analytics job. It helps to decide early whether invalid values should fail fast, be logged and skipped, or become missing values for later review.

That policy choice matters because conversion is not only about syntax. It is also about how your system handles bad data once it arrives.

Common Pitfalls

The biggest mistake is assuming every numeric-looking string will work with float. Formatted values with commas, units, or unexpected separators often fail.

Another issue is swallowing ValueError and defaulting silently to zero, which hides upstream data problems.

A third problem is using float for money when exact decimal behavior matters more than speed.

Summary

  • Use float(text) for ordinary numeric strings in Python.
  • Strip whitespace and catch ValueError for robust parsing.
  • Clean formatting noise before conversion when necessary.
  • Validate nan and inf if only finite values are allowed.
  • Use Decimal instead of float when exact base-10 arithmetic matters.

Course illustration
Course illustration

All Rights Reserved.