string conversion
integer conversion
data types
programming tutorial
coding basics

Convert a string into an int

Master System Design with Codemia

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

Introduction

Converting a string to an integer is one of the most common operations in programming. Every language provides built-in functions for this: Python uses int(), JavaScript uses parseInt() or Number(), Java uses Integer.parseInt(), C# uses int.Parse() or int.TryParse(), and C/C++ use atoi() or stoi(). The key considerations are handling invalid input (non-numeric strings), dealing with different number bases (hex, octal, binary), and understanding overflow behavior when the number exceeds the integer range.

Python

python
1# Basic conversion
2num = int("42")      # 42
3neg = int("-17")     # -17
4
5# With whitespace — works automatically
6num = int("  42  ")  # 42
7
8# Different bases
9hex_val = int("ff", 16)   # 255
10oct_val = int("77", 8)    # 63
11bin_val = int("1010", 2)  # 10
12
13# Auto-detect base with 0x, 0o, 0b prefix
14auto = int("0xff", 0)     # 255
15
16# Error handling
17try:
18    num = int("hello")
19except ValueError:
20    print("Not a valid integer")
21
22# Safe conversion function
23def safe_int(s, default=0):
24    try:
25        return int(s)
26    except (ValueError, TypeError):
27        return default
28
29safe_int("42")       # 42
30safe_int("abc")      # 0
31safe_int(None)       # 0

Python's int() raises ValueError for invalid strings. Python integers have arbitrary precision — no overflow.

JavaScript

javascript
1// parseInt — stops at first non-digit
2parseInt("42")         // 42
3parseInt("42abc")      // 42 (ignores trailing non-digits)
4parseInt("abc42")      // NaN (starts with non-digit)
5
6// Always specify the radix
7parseInt("010", 10)    // 10 (decimal)
8parseInt("010", 8)     // 8  (octal)
9parseInt("ff", 16)     // 255 (hex)
10
11// Number() — stricter, converts entire string
12Number("42")           // 42
13Number("42abc")        // NaN (unlike parseInt)
14Number("")             // 0 (empty string is 0)
15Number(" 42 ")         // 42 (trims whitespace)
16
17// Unary plus — shorthand for Number()
18+"42"                  // 42
19+"abc"                 // NaN
20
21// Check for NaN
22const result = parseInt(input, 10);
23if (Number.isNaN(result)) {
24    console.log("Invalid number");
25}
26
27// Math.trunc for float strings
28Math.trunc(Number("3.14"))  // 3
29parseInt("3.14", 10)        // 3

Always pass the radix (base) to parseInt to avoid unexpected octal/hex parsing.

Java

java
1// Integer.parseInt — returns int primitive
2int num = Integer.parseInt("42");       // 42
3int neg = Integer.parseInt("-17");      // -17
4int hex = Integer.parseInt("ff", 16);   // 255
5
6// Integer.valueOf — returns Integer object (cached for -128 to 127)
7Integer obj = Integer.valueOf("42");
8
9// Error handling
10try {
11    int num = Integer.parseInt("hello");
12} catch (NumberFormatException e) {
13    System.out.println("Invalid: " + e.getMessage());
14}
15
16// Overflow — throws NumberFormatException
17try {
18    int big = Integer.parseInt("9999999999");
19} catch (NumberFormatException e) {
20    // Number too large for int
21    long bigLong = Long.parseLong("9999999999");  // Use long instead
22}
23
24// Safe parsing utility
25public static OptionalInt tryParse(String s) {
26    try {
27        return OptionalInt.of(Integer.parseInt(s));
28    } catch (NumberFormatException e) {
29        return OptionalInt.empty();
30    }
31}

C#

csharp
1// int.Parse — throws on invalid input
2int num = int.Parse("42");       // 42
3int hex = int.Parse("ff", System.Globalization.NumberStyles.HexNumber);  // 255
4
5// int.TryParse — returns bool, no exception
6if (int.TryParse("42", out int result))
7{
8    Console.WriteLine(result);  // 42
9}
10else
11{
12    Console.WriteLine("Invalid number");
13}
14
15// TryParse is preferred for user input
16string input = Console.ReadLine();
17int value = int.TryParse(input, out int v) ? v : 0;
18
19// Convert class
20int num2 = Convert.ToInt32("42");
21int fromNull = Convert.ToInt32(null);  // Returns 0 (doesn't throw)

int.TryParse is the idiomatic C# approach for user input — it avoids exception overhead for invalid strings.

C / C++

cpp
1#include <cstdlib>   // atoi, strtol
2#include <string>    // stoi
3
4// C: atoi — no error detection
5int num = atoi("42");       // 42
6int bad = atoi("hello");    // 0 (no way to distinguish from "0")
7
8// C: strtol — with error detection
9char *end;
10long val = strtol("42abc", &end, 10);
11// val = 42, *end = 'a' (points to first invalid character)
12if (*end != '\0') {
13    // String was not fully consumed
14}
15
16// C++: std::stoi — throws on invalid input
17try {
18    int num = std::stoi("42");       // 42
19    int hex = std::stoi("ff", nullptr, 16);  // 255
20} catch (std::invalid_argument& e) {
21    // No conversion could be performed
22} catch (std::out_of_range& e) {
23    // Value out of int range
24}
25
26// C++17: std::from_chars — fastest, no allocation
27#include <charconv>
28std::string_view sv = "42";
29int result;
30auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), result);
31if (ec == std::errc()) {
32    // Success: result = 42
33}

Common Pitfalls

  • Not specifying radix in JavaScript parseInt: parseInt("010") may return 8 (octal) in older environments. Always pass the radix explicitly: parseInt("010", 10) returns 10. This is one of JavaScript's most common gotchas.
  • Using atoi in C for untrusted input: atoi returns 0 for both the string "0" and any invalid string like "hello". There is no way to detect errors. Use strtol with an end pointer, or std::stoi in C++.
  • Ignoring overflow: In Java and C#, parsing a number larger than Integer.MAX_VALUE / int.MaxValue throws an exception. In C, atoi has undefined behavior on overflow. In JavaScript, parseInt returns Infinity for extremely large strings. Always consider the valid range.
  • Empty strings: int("") in Python raises ValueError. parseInt("") in JavaScript returns NaN. Integer.parseInt("") in Java throws NumberFormatException. Always validate that the string is non-empty before converting.
  • Floating-point strings: int("3.14") in Python raises ValueError (use int(float("3.14"))). parseInt("3.14") in JavaScript returns 3 (truncates). Integer.parseInt("3.14") in Java throws. Know how your language handles decimal strings when you expect an integer.

Summary

  • Python: int(s) — raises ValueError on invalid input, supports arbitrary precision
  • JavaScript: parseInt(s, 10) — always specify radix, returns NaN on failure
  • Java: Integer.parseInt(s) — throws NumberFormatException on invalid input
  • C#: int.TryParse(s, out result) — preferred for user input, avoids exceptions
  • C++: std::stoi(s) or std::from_chars() — prefer over atoi for error detection

Course illustration
Course illustration

All Rights Reserved.