SoftwareSideHustles
How-To

How to Convert an Int to a String (and Back) in Python, JavaScript, Java, C#, Go, C++ and Rust

The one-line answer for converting an integer to a string and parsing it back in nine languages, plus the edge cases that cause real bugs — whitespace, invalid input, leading zeros and locale formatting.

By Software Side Hustles Editorial Team · Published · Updated · 6 min read

Quick answer: use the language's built-in conversion — str(n) in Python, String(n) in JavaScript, String.valueOf(n) in Java, n.ToString() in C#, strconv.Itoa(n) in Go, std::to_string(n) in C++ and n.to_string() in Rust. Going the other way (string → int) is where the bugs live, because the input might not be a number at all.

Int to string and string to int: the cheat sheet

LanguageInt → stringString → intInvalid input does…
Pythonstr(n) or f"{n}"int(s)raises ValueError
JavaScript / TypeScriptString(n) or `${n}`Number(s) or parseInt(s, 10)returns NaN
JavaString.valueOf(n)Integer.parseInt(s)throws NumberFormatException
C#n.ToString()int.Parse(s) / int.TryParse(s, out var n)throws FormatException / returns false
Gostrconv.Itoa(n)strconv.Atoi(s)returns a non-nil error
C++std::to_string(n)std::stoi(s)throws std::invalid_argument
Rustn.to_string()s.parse::<i32>()returns Err(ParseIntError)
Kotlinn.toString()s.toInt() / s.toIntOrNull()throws / returns null
Rubyn.to_sInteger(s)raises ArgumentError (s.to_i silently returns 0)

The rest of this guide covers each language and the mistakes worth knowing about.

How do I convert an int to a string in Python?

python
n = 42
s1 = str(n) # '42'
s2 = f"{n}" # '42'
s3 = f"{n:05d}" # '00042' zero-padded to width 5
s4 = f"{1234567:,}" # '1,234,567' thousands separator
s5 = format(255, "x") # 'ff' hexadecimal

And back again:

python
int("42") # 42
int(" 42\n") # 42 — surrounding whitespace is allowed
int("1_000") # 1000 — underscores between digits are allowed
int("ff", 16) # 255
int("4.2") # ValueError: invalid literal for int() with base 10: '4.2'
int(float("4.2")) # 4 — truncates towards zero

Wrap parsing of user input in try/except ValueError. One newer gotcha: since Python 3.11, converting an integer with more than 4,300 digits to a string raises ValueError: Exceeds the limit (4300 digits) for integer string conversion. It is a denial-of-service protection; sys.set_int_max_str_digits() raises the limit if you genuinely need huge numbers.

How do I convert a number to a string in JavaScript?

javascript
const n = 42;
String(n); // "42"
n.toString(); // "42"
`${n}`; // "42"
n.toString(2); // "101010" binary
n.toString().padStart(5, "0"); // "00042"

String(value) is the safest because it also works for null and undefined ("null", "undefined"), whereas null.toString() throws a TypeError.

Parsing back is full of traps:

javascript
Number("42"); // 42
Number("42px"); // NaN — the whole string must be numeric
parseInt("42px", 10); // 42 — parses the leading digits and stops
Number(""); // 0 — an empty string is NOT NaN
Number(" "); // 0
parseInt(0.0000005); // 5 — the number is stringified to "5e-7" first

Rules of thumb: use Number() when the whole string must be a number, always pass the radix to parseInt and only ever pass it strings, and check the result with Number.isNaN() (or Number.isInteger() when you need an integer). Treat empty strings explicitly, because Number("") quietly gives you zero.

How do I convert an int to a String in Java?

java
int n = 42;
String a = String.valueOf(n); // "42"
String b = Integer.toString(n); // "42"
String c = "" + n; // works, but less clear
String d = String.format("%05d", n); // "00042"
String hex = Integer.toString(255, 16); // "ff"

Parsing:

java
int x = Integer.parseInt("42"); // 42 (primitive int)
Integer y = Integer.valueOf("42"); // 42 (boxed Integer)
Integer.parseInt(" 42"); // NumberFormatException — no trimming
Integer.parseInt("3000000000"); // NumberFormatException — overflows int
long big = Long.parseLong("3000000000");

Java does not trim for you, so call s.strip() first when the input comes from a file or form. Values outside the int range also fail, which surprises people parsing IDs or timestamps — use Long.parseLong for those.

How do I convert an int to a string in C#?

csharp
int n = 42;
string a = n.ToString(); // "42"
string b = $"{n}"; // "42"
string c = n.ToString("D5"); // "00042"
string d = 1234567.ToString("N0", CultureInfo.InvariantCulture); // "1,234,567"
if (int.TryParse(input, out var value)) { /* use value */ }

Prefer int.TryParse for anything a user typed; it returns false instead of throwing. When formatting numbers for machines (files, APIs, logs that get parsed), pass CultureInfo.InvariantCulture — otherwise a server running with a German locale will happily write 1.234.567.

Go, C++ and Rust

Go returns errors instead of throwing:

go
s := strconv.Itoa(42) // "42"
n, err := strconv.Atoi("42") // 42, nil
if err != nil { /* handle */ }
big, err := strconv.ParseInt("3000000000", 10, 64)

The classic Go mistake is string(65), which produces "A" — the character with code point 65 — not "65". go vet flags it ("conversion from int to string yields a string of one rune"); use strconv.Itoa.

C++ has std::to_string(42) and std::stoi("42"). std::stoi throws std::invalid_argument for non-numeric input and std::out_of_range on overflow, and it stops at the first non-digit, so std::stoi("42abc") returns 42. For fast, non-throwing parsing use std::from_chars (C++17), and for formatting std::format("{:05}", n) (C++20).

Rust makes failure explicit in the type:

rust
let s = 42.to_string(); // "42"
let n: i32 = "42".parse().unwrap(); // 42
let bad = "4x".parse::<i32>(); // Err(ParseIntError { kind: InvalidDigit })

Common mistakes when converting between numbers and strings

  1. Assuming input is clean. Real input has spaces, newlines, thousands separators and empty strings. Decide what you accept, then validate.
  2. Silent defaults. Ruby's "abc".to_i, PHP's intval("abc") and JavaScript's Number("") all return 0. A zero that should have been an error can corrupt data quietly.
  3. Losing leading zeros. Postcodes, phone numbers and account numbers are identifiers, not numbers. Converting "007" to an int and back gives "7". Keep identifiers as strings.
  4. Overflow. Parsing "3000000000" into a 32-bit int fails or wraps depending on the language. Pick a 64-bit type for IDs and timestamps.
  5. Locale. Formatting with the user's locale is right for display and wrong for storage.
  6. Floats in disguise. "4.2" is not an integer. Decide whether to reject it, round it or truncate it — and make that choice explicit. See how to round to two decimal places correctly.

Frequently asked questions

What is the fastest way to convert an int to a string?

In practice the built-in function — str(), String(), String.valueOf(), strconv.Itoa(). Micro-differences between, say, str(n) and an f-string are irrelevant outside very hot loops; choose the clearest option.

How do I check whether a string is a valid integer?

Try to parse it and handle the failure: try: int(s) in Python, int.TryParse in C#, strconv.Atoi with an error check in Go, or Number.isInteger(Number(s)) && s.trim() !== "" in JavaScript. A regular expression such as ^-?\d+$ works too, but it does not catch overflow.

Why does parseInt return a number for "42px"?

parseInt reads digits from the start of the string and stops at the first character it cannot use. Number("42px") is stricter and returns NaN.

How do I keep leading zeros?

Format with a width: f"{n:05d}" (Python), String.format("%05d", n) (Java), n.ToString("D5") (C#), String(n).padStart(5, "0") (JavaScript). If the value is an identifier, store it as a string in the first place.

Where this skill pays off

Spotting that Number("") returns 0, or that Integer.parseInt will not trim a newline, is exactly the kind of detail that separates a correct answer from a plausible one. Developers who notice these things are paid to review AI-generated code — see how software engineers earn money training AI models, or try the free code review practice lab.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy