How to Convert a String to Int: A Complete Guide for Every Language

Converting a string to an integer is one of the most common tasks in programming — and one of the easiest to get wrong if you don't understand what's happening under the hood. Whether you're parsing user input, reading data from a file, or processing values from an API response, knowing how and when to convert string data to integer format is a fundamental skill.

What Does "String to Int" Actually Mean?

In programming, a string is a sequence of characters — text. An integer is a whole number stored in a numeric data type. When data comes in as text (which it often does from forms, files, URLs, or APIs), the value "42" and the number 42 are completely different things to your program.

If you try to do math with "42" as a string, you'll get unexpected results or an outright error. Converting it to an integer tells the program: treat this as a number, not text.

Why Strings Often Need Converting

Data arrives as strings more often than you might expect:

  • User input fields always return strings, even if the user typed a number
  • CSV or text file values are read as raw text
  • URL parameters are strings by default
  • JSON values may be strings depending on how the data was structured
  • Environment variables are always strings

This is why string-to-int conversion shows up constantly across nearly every real-world programming task.

How to Convert a String to Int by Language

The method varies depending on which language you're working in. Here's how it works across the most common ones:

LanguageCommon MethodExample
Pythonint()int("42")42
JavaScriptparseInt() or Number()parseInt("42")42
JavaInteger.parseInt()Integer.parseInt("42")42
C#int.Parse() or Convert.ToInt32()int.Parse("42")42
PHP(int) cast or intval()(int)"42"42
Ruby.to_i"42".to_i42
Gostrconv.Atoi()strconv.Atoi("42")42, nil
SwiftInt() initializerInt("42")42

Each language handles this differently, but the underlying concept is the same: parse the character sequence and produce a numeric value.

What Happens When the String Isn't a Valid Number 🚨

This is where things get interesting — and where bugs are born.

If you try to convert "hello" or "42abc" to an integer, most languages will either throw an error or return a fallback value. The behavior depends on the language:

  • Python raises a ValueError if the string isn't a valid integer
  • JavaScript's parseInt() returns NaN (Not a Number) for invalid input
  • Java throws a NumberFormatException
  • Ruby's .to_i silently returns 0 if conversion fails
  • Go's strconv.Atoi() returns an error value you're expected to check

This inconsistency matters. A language that silently returns 0 won't crash your program — but it might produce incorrect results that are harder to debug than an outright error. Understanding your language's failure behavior is just as important as knowing the conversion method itself.

Handling Errors and Edge Cases

Robust code always accounts for failed conversions. Common patterns include:

Try/Except (Python):

try: value = int(user_input) except ValueError: print("That's not a valid number.") 

Conditional check (JavaScript):

const value = parseInt(input); if (isNaN(value)) { console.log("Invalid number"); } 

Safe parsing with error return (Go):

value, err := strconv.Atoi(input) if err != nil { // handle the error } 

The right approach depends on your language and whether a failed conversion should halt execution, return a default, or be surfaced to the user.

Radix and Base: A Detail That Trips People Up

In some languages — particularly JavaScript — the parseInt() function accepts a second argument called the radix, which specifies the numeric base.

parseInt("10", 2) returns 2, because "10" in base 2 (binary) equals 2 in decimal.

If you omit the radix in JavaScript, the function makes a guess, which can produce surprising results with strings that start with 0. Always pass the radix explicitly when using parseInt() in JavaScript — for standard decimal integers, that means parseInt(value, 10).

Floats, Decimals, and What Int Conversion Ignores 🔢

It's worth knowing that converting "3.7" to an integer won't round it — most languages will either:

  • Truncate toward zero (so "3.7" becomes 3, not 4)
  • Throw an error because "3.7" isn't a valid integer string

If your string contains a decimal number and you need the integer equivalent, you may need to convert to a float first, then explicitly round or truncate before converting to int.

The Variables That Shape Your Approach

The "right" way to convert a string to an integer shifts based on several factors:

  • Language — each has its own syntax and failure behavior
  • Data source — input from users is less predictable than values from a controlled API
  • Error tolerance — a background data pipeline may handle failures differently than user-facing code
  • Numeric base — most use cases are base 10, but file permissions, color codes, and binary data may not be
  • Scale of values — very large numbers may overflow standard integer types in some languages, requiring long or BigInt alternatives
  • Type strictness — statically typed languages enforce types at compile time; dynamically typed ones may only surface issues at runtime

A developer parsing a single form field has a very different set of concerns than someone building a data pipeline processing millions of records from external sources.

What conversion method fits best ultimately comes down to what your code is doing, where the data is coming from, and how your program should behave when something unexpected shows up.