Converting a string to an integer means telling your program to treat text that looks like a number as an actual number you can do math with
When you read data from a file, a form, or user input, it usually arrives as text — even if that text is "42" or "1000". Your code cannot add, subtract, or compare text the way it handles real numbers. Converting a string to an integer (often called "casting" or "parsing") transforms that text into a number your program can calculate with.
The method you use depends on which programming language you are writing in. Python, JavaScript, Java, C++, and other languages each have their own built-in functions for this task. The basic idea is the same everywhere: you pass the text to a conversion function, and it returns a number — or an error if the text does not look like a number.
Key Takeaways
- Python uses int() to convert text to a number, and it will stop with an error if the text contains letters or special characters.
- JavaScript uses parseInt() or Number(), and parseInt() ignores non-numeric characters at the end of the string.
- Java uses Integer.parseInt() or Integer.valueOf(), and both throw an exception if the conversion fails.
- Always check whether the conversion succeeded before using the result, because bad input will crash your program if you do not handle the error.
- Leading and trailing spaces are usually ignored, but letters, punctuation, and currency symbols will cause the conversion to fail.
Converting strings in Python
In Python, the int() function converts a string to an integer. Write the string inside the parentheses: int("42") returns the number 42. You can also specify a base — int("1010", 2) converts the binary string "1010" to 10 in decimal.
If the string contains anything that is not a number, Python raises a ValueError and stops running. int("42a") will crash unless you catch the error. The safest approach is to wrap the conversion in a try-except block:
try: number = int(user_input) except ValueError: print("That is not a valid number")
Python ignores leading and trailing spaces, so int(" 42 ") works fine. Negative numbers work too: int("-42") returns -42.
Converting strings in JavaScript
JavaScript offers two main functions: parseInt() and Number(). They behave differently when the input is messy.
parseInt() reads from the left and stops at the first non-numeric character. parseInt("42px") returns 42, ignoring the "px". This is useful when parsing measurements or other formatted text. You can also pass a second argument for the base: parseInt("1010", 2) converts binary to decimal. If the string starts with a letter, parseInt returns NaN (not a number).
Number() is stricter. Number("42") returns 42, but Number("42px") returns NaN. Use Number() when you need the entire string to be numeric. Both functions ignore leading and trailing spaces.
Always check the result before using it: if (isNaN(result)) { /* handle error */ }
Converting strings in Java
Java provides Integer.parseInt() and Integer.valueOf(). Both convert a string to an integer, but they behave slightly differently.
Integer.parseInt("42") returns the primitive int type 42. Integer.valueOf("42") returns an Integer object (a wrapper around the primitive). For most purposes, they work the same way. Both throw a NumberFormatException if the string is not a valid number, so you must catch it:
try { int number = Integer.parseInt(userInput); } catch (NumberFormatException e) { System.out.println("Invalid number"); }
You can also specify a base as a second argument: Integer.parseInt("1010", 2) converts binary to decimal. Java ignores leading and trailing spaces.
Converting strings in C++
C++ has several options depending on your standard library version. The modern approach uses std::stoi() (string to integer):
int number = std::stoi("42");
std::stoi() throws an exception if the conversion fails, so wrap it in a try-catch block. It also accepts a second argument for the base: std::stoi("1010", nullptr, 2) converts binary. The function stops reading at the first non-numeric character and ignores leading spaces.
Older C++ code often uses atoi(), which is simpler but less safe — it returns 0 if the conversion fails, making it hard to tell whether the input was actually "0" or invalid. Avoid atoi() in new code.
Handling errors and edge cases
The most common mistake is assuming the conversion will always work. If a user types "abc" when you ask for a number, your program will crash unless you handle the error. Every language provides a way to catch conversion failures — use it every time.
Spaces at the start and end are almost always ignored, so " 42 " converts fine. Negative numbers work in all languages: "-42" becomes -42. Very large numbers may overflow if they exceed the maximum value an integer can hold — in Python this is not a problem, but in Java, C++, and JavaScript it is. If you expect very large numbers, use a bigger data type (long in Java, BigInt in JavaScript).
Decimal points cause conversion to fail in all languages. int("42.5") crashes in Python and Java. If you need to handle decimals, convert to a float or double first, then round or truncate to an integer.
Choosing between conversion methods
Use int() in Python when you want strict conversion — fail fast if the input is bad. Use parseInt() in JavaScript when you are parsing formatted text like "42px" and want to extract the number. Use Number() in JavaScript when you need the entire string to be numeric. In Java, Integer.parseInt() is the standard choice for most cases. In C++, use std::stoi() for modern code.
The key is to always wrap the conversion in error handling. A program that crashes on bad input is worse than one that rejects the input and asks the user to try again.
Frequently Asked Questions
What happens if I try to convert a string with letters in it?
In Python and Java, the conversion fails and raises an error. In JavaScript, parseInt() returns the number it read before hitting the letter, while Number() returns NaN. In C++, std::stoi() throws an exception. Always check the result or use error handling.
Can I convert a string with spaces to an integer?
Yes. Leading and trailing spaces are ignored in all major languages, so " 42 " converts to 42. Spaces in the middle (like "4 2") will cause the conversion to fail.
What is the difference between parseInt and Number in JavaScript?
parseInt() stops reading at the first non-numeric character, so parseInt("42px") returns 42. Number() requires the entire string to be numeric, so Number("42px") returns NaN. Use parseInt() for formatted text and Number() when you need strict validation.
How do I convert a binary or hexadecimal string to an integer?
Most languages let you pass a base as a second argument. In Python: int("1010", 2) converts binary. In JavaScript: parseInt("FF", 16) converts hexadecimal. In Java: Integer.parseInt("1010", 2) does the same. Check your language's documentation for the exact syntax.
What should I do if the conversion fails?
Always use error handling. Wrap the conversion in a try-catch block (Python, Java, C++) or check the result with isNaN() (JavaScript). Tell the user the input was invalid and ask them to enter a number again, rather than letting the program crash.