May 27, 2026

How to convert string to number in Python and JS

Reading time :  
7
 min
Osman Ramadan
Osman Ramadan

How to convert string to number in Python and JavaScript

Knowing how to convert string to number sounds like a beginner topic until a webhook payload sends you "1,234.56" as a string and your arithmetic returns NaN. String-to-number conversion is the most common type coercion in data processing — and the most frequently botched. A 2025 analysis by Snyk found that type-related bugs account for 18% of runtime errors in production Node.js applications. In Python, the story is similar: implicit type assumptions cause silent failures in data pipelines every day. CodeWords microservices handle these conversions inside serverless Python endpoints, giving you a controlled environment to parse, validate, and transform data types without building infrastructure.

Unlike generic AI automation posts, this guide shows real CodeWords workflows — not just theory.

TL;DR

  • Python uses int(), float(), and Decimal() for string-to-number conversion; each has different precision and error behavior.
  • JavaScript's parseInt(), parseFloat(), and Number() have subtle gotchas — parseInt("08") works now, but parseInt("") returns NaN while Number("") returns 0.
  • Build validation-first conversion functions and deploy them as reusable CodeWords microservices.

Why does string-to-number conversion matter in automation?

Data moving through automation workflows is a river that changes shape at every bend. APIs return JSON where numbers arrive as strings. CSV files have no type system — everything is text. Form submissions, webhook payloads, database query results with string columns — they all produce numbers that aren't actually numbers yet.

The cost of getting this wrong ranges from incorrect calculations to crashed workflows. Silently wrong is worse than loudly broken: if your revenue report adds "100" + "200" as string concatenation and returns "100200" instead of 300, nobody gets an error message. You just get a report that's off by orders of magnitude.

How do you convert string to number in Python?

Prerequisites

Step 1: Basic conversion with int() and float()

integer_value = int("42")        # 42
float_value = float("3.14")     # 3.14
negative = int("-7")            # -7
scientific = float("1.5e3")    # 1500.0

These work for clean input. Real-world data is rarely clean.

Step 2: Handle locale-specific number formats

European numbers use commas as decimal separators and dots as thousands separators — the opposite of US formatting.

def parse_number(s: str, locale: str = "us") -> float:
    s = s.strip()
    if locale == "eu":
        s = s.replace(".", "").replace(",", ".")
    else:
        s = s.replace(",", "")
    return float(s)

print(parse_number("1,234.56", "us"))   # 1234.56
print(parse_number("1.234,56", "eu"))   # 1234.56

Step 3: Use Decimal for financial data

from decimal import Decimal

price = Decimal("19.99")
tax = Decimal("0.08")
total = price * (1 + tax)
print(total)  # 21.5892 (exact, no floating-point drift)

The Decimal class avoids the classic 0.1 + 0.2 = 0.30000000000000004 problem. For any workflow involving money, invoices, or financial calculations, Decimal isn't optional — it's required.

Step 4: Build a safe conversion function

from decimal import Decimal, InvalidOperation
from typing import Union

def safe_to_number(value: str, allow_float: bool = True) -> Union[int, float, None]:
    if not isinstance(value, str) or not value.strip():
        return None
    cleaned = value.strip().replace(",", "")
    try:
        if allow_float and ("." in cleaned or "e" in cleaned.lower()):
            return float(cleaned)
        return int(cleaned)
    except (ValueError, InvalidOperation):
        return None

print(safe_to_number("42"))       # 42
print(safe_to_number("3.14"))     # 3.14
print(safe_to_number("abc"))      # None
print(safe_to_number(""))         # None

How do you convert string to number in JavaScript?

JavaScript offers three main approaches, each with different behavior on edge cases.

parseInt and parseFloat

parseInt("42")          // 42
parseInt("42px")        // 42 (stops at non-digit)
parseInt("")            // NaN
parseFloat("3.14")      // 3.14
parseFloat("3.14.15")   // 3.14 (stops at second dot)

Always pass a radix to parseInt:

parseInt("08", 10)      // 8 (explicit base-10)

Number() constructor

Number("42")            // 42
Number("42px")          // NaN (stricter than parseInt)
Number("")              // 0 (gotcha!)
Number(null)            // 0 (another gotcha!)
Number(undefined)       // NaN

The Number("") returning 0 is a source of bugs in validation logic. If you're checking whether a form field has a value, Number(emptyString) will pass a !== 0 check as false.

Unary plus operator

+"42"                   // 42
+"3.14"                 // 3.14
+""                     // 0 (same gotcha as Number)

Concise but less readable. Use Number() for clarity in production code.

Safe JavaScript conversion

function safeToNumber(value) {
  if (typeof value !== "string" || value.trim() === "") return null;
  const cleaned = value.trim().replace(/,/g, "");
  const num = Number(cleaned);
  return Number.isFinite(num) ? num : null;
}

safeToNumber("42")       // 42
safeToNumber("abc")      // null
safeToNumber("")         // null
safeToNumber("1,234.56") // 1234.56

How do you handle conversions in CodeWords workflows?

Inside CodeWords, string-to-number conversion typically happens at two points: ingestion (parsing incoming data) and transformation (preparing data for downstream systems).

Step 1: Build a conversion microservice

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class ConvertRequest(BaseModel):
    value: str
    locale: str = "us"
    precision: int = 2

@app.post("/convert")
def convert(req: ConvertRequest):
    cleaned = req.value.strip()
    if req.locale == "eu":
        cleaned = cleaned.replace(".", "").replace(",", ".")
    else:
        cleaned = cleaned.replace(",", "")
    try:
        result = round(float(cleaned), req.precision)
        return {"success": True, "result": result, "type": "float"}
    except ValueError:
        return {"success": False, "error": f"Cannot convert '{req.value}' to number"}

Deploy this to CodeWords and call it from any workflow — webhook processing, spreadsheet imports, or API data transformation.

Step 2: Batch convert columns

When processing CSV or Excel files from Google Drive:

import pandas as pd

def clean_numeric_column(series: pd.Series, locale: str = "us") -> pd.Series:
    if locale == "eu":
        return pd.to_numeric(
            series.str.replace(".", "", regex=False).str.replace(",", ".", regex=False),
            errors="coerce"
        )
    return pd.to_numeric(series.str.replace(",", "", regex=False), errors="coerce")

df = pd.read_csv("sales.csv")
df["revenue"] = clean_numeric_column(df["revenue"], locale="eu")

The errors="coerce" parameter converts unparseable values to NaN instead of raising exceptions — letting you identify and handle bad data after the fact.

What are the common edge cases?

Edge cases that break string-to-number conversion in production:

  • Currency symbols: "$1,234", "€1.234,56", "£999" — strip symbols before parsing
  • Percentage signs: "45%" — strip the % and divide by 100 if needed
  • Whitespace: " 42 ", "4\u00a02" (non-breaking space) — always .strip() and handle unicode spaces
  • Boolean strings: "true" or "false" — decide whether these map to 1/0 or raise an error
  • Infinity and NaN: "Infinity", "NaN" — Python's float() actually parses these, which may not be what you want

According to Python's official documentation, float("inf") and float("nan") are valid. Add explicit checks if your workflow shouldn't accept infinite values.

How do you validate before converting?

Validation should happen before conversion, not after. A regex pre-check catches most issues:

import re

NUMBER_PATTERN = re.compile(r"^-?\d{1,3}(,\d{3})*(\.\d+)?$|^-?\d+(\.\d+)?$")

def is_valid_number(s: str) -> bool:
    return bool(NUMBER_PATTERN.match(s.strip()))

print(is_valid_number("1,234.56"))  # True
print(is_valid_number("abc"))       # False
print(is_valid_number("12.34.56"))  # False

Integrate this validation into your CodeWords data pipeline. Route invalid records to an error queue with Slack alerts, and process valid records normally.

FAQs

What's the difference between parseInt and Number in JavaScript?

parseInt parses until it hits a non-numeric character (parseInt("42px") returns 42). Number requires the entire string to be numeric (Number("42px") returns NaN). Use Number when you need strict validation.

How do I handle numbers with different decimal separators?

Detect the locale from context (user settings, data source metadata, or column headers), then normalize: strip the thousands separator, replace the decimal separator with a dot, and parse as float.

Should I use int() or float() in Python?

Use int() when you know the value is a whole number. Use float() for decimals. Use Decimal() for financial calculations. When uncertain, parse as float and check float.is_integer() to decide.

How does CodeWords handle type conversion in integrations?

CodeWords integrations via Composio and Pipedream handle common type coercions automatically. For custom logic, build a conversion microservice (like the examples above) and wire it into your workflow.

Conclusion

String-to-number conversion isn't a problem you solve once — it's a boundary condition you handle every time data crosses a system boundary. The right approach is a validation-first conversion layer that sits at your ingestion point, normalizes formats, catches edge cases, and routes errors before they propagate. Build your data conversion layer in CodeWords — because the next webhook payload is already on its way, and it definitely has a comma where you're expecting a dot.

Contents
Ready to try CodeWords?
Get started free
Sign in
Sign in