Question
How do I convert a string value into an integer in JavaScript? What are the correct ways to do this, and how do they behave with different kinds of input such as whitespace, decimals, or non-numeric characters?
Short Answer
By the end of this page, you will understand how JavaScript converts strings to integers, when to use parseInt() versus Number(), how invalid input behaves, and which common mistakes to avoid when working with numeric strings.
Concept
In JavaScript, values often come in as strings even when they look like numbers. This happens frequently with form inputs, API responses, query parameters, and JSON data.
If you need to do math, compare numeric values correctly, or store data in a number-based format, you usually need to convert the string into a number first.
For integers specifically, the most common tools are:
parseInt(string, radix)Number(string)- Unary plus:
+string Math.trunc(Number(string))when you need to remove decimals after conversion
These methods are not identical.
parseInt()
parseInt() reads a string from left to right and tries to extract an integer. It stops when it reaches a character that does not belong in the number.
parseInt("42", 10); // 42
parseInt("42px", 10); // 42
parseInt("3.9", 10); // 3
parseInt("abc", 10); // NaN
This makes it useful when the string may contain extra text after the number.
Number()
Number() tries to convert the entire string into a number. If the whole string is not a valid number, it returns NaN.
Number("42"); // 42
Number("3.9"); // 3.9
Number("42px"); // NaN
This is better when you want strict conversion.
Unary plus
Unary plus is a short form of Number().
+"42"; // 42
+"3.9"; // 3.9
+"abc"; // NaN
Why this matters
If you forget to convert strings, JavaScript may treat them as text instead of numbers.
"2" + "3"; // "23"
"2" * "3"; // 6
That inconsistency is why explicit conversion is a good habit. It makes your code clearer and more predictable.
Mental Model
Think of a numeric string as a number written on a piece of paper.
Number()checks whether the entire paper contains a valid number.parseInt()starts reading from the beginning and keeps going until something stops it.- Unary
+is a quick shortcut that behaves likeNumber().
So if the paper says:
"42"→ all methods can understand it"42px"→parseInt()reads42, butNumber()rejects it"3.9"→Number()reads3.9, whileparseInt()keeps only the integer part3
A useful rule is:
- Use
Number()when the whole string must be numeric - Use
parseInt()when you want to extract an integer from the start of a string
Syntax and Examples
Here are the main ways to convert a string to an integer in JavaScript.
Using parseInt()
const value = "123";
const result = parseInt(value, 10);
console.log(result); // 123
Why include 10?
The second argument is the radix, which means the number base.
10= decimal2= binary16= hexadecimal
For normal integer conversion, use 10.
Using Number() and then removing decimals if needed
const value = "123";
const result = Number(value);
console.log(result); // 123
If you specifically need an integer and want to drop the decimal part:
Step by Step Execution
Consider this example:
const input = "15px";
const result = parseInt(input, 10);
console.log(result);
Step by step:
inputstores the string"15px"parseInt(input, 10)begins reading from the start of the string- It sees
1, which is valid in base 10 - It sees
5, which is also valid in base 10 - It sees
p, which is not valid in a decimal integer - It stops reading at that point
- It returns the integer
15 console.log(result)prints15
Now compare with Number():
const input = "15px";
const result = Number(input);
console.(result);
Real World Use Cases
String-to-integer conversion appears in many common programming tasks.
Form input values
HTML form fields return strings.
const age = "25";
const ageNumber = Number(age);
You need conversion before validation or calculations.
Query parameters
URLs often store numbers as text.
const page = "3";
const pageNumber = parseInt(page, 10);
This is common in pagination.
CSS-related values
Sometimes a value may contain units.
const width = "200px";
const numericWidth = parseInt(width, 10);
Reading data from APIs
Even when a field represents a number, some APIs send it as a string.
const price = "499";
const numericPrice = Number(price);
Real Codebase Usage
In real projects, developers usually do more than just convert. They also validate the result and handle bad input safely.
Validation pattern
const input = "42";
const value = Number(input);
if (Number.isNaN(value)) {
console.log("Invalid number");
} else {
console.log("Valid number:", value);
}
Guard clause for invalid input
function getUserAge(ageInput) {
const age = Number(ageInput);
if (Number.isNaN(age)) {
throw new Error("Age must be a valid number");
}
return Math.trunc(age);
}
Parsing configuration values
Environment variables are strings.
rawPort = process.. || ;
port = (rawPort);
(.(port)) {
();
}
Common Mistakes
1. Forgetting that form values are strings
const a = "2";
const b = "3";
console.log(a + b); // "23"
Fix
console.log(Number(a) + Number(b)); // 5
2. Using parseInt() when strict conversion is needed
parseInt("123abc", 10); // 123
If you want invalid input to fail, use Number() instead.
Number("123abc"); // NaN
3. Forgetting the radix in parseInt()
Always write:
(, );
Comparisons
| Method | Example | Result with "42" | Result with "42px" | Result with "3.9" | Best use |
|---|---|---|---|---|---|
parseInt(value, 10) | parseInt("42", 10) | 42 | 42 | 3 | Extracting an integer from the start of a string |
Number(value) | Number("42") | 42 |
Cheat Sheet
Quick reference
parseInt("123", 10); // 123
Number("123"); // 123
+"123"; // 123
Math.trunc(Number("3.9")); // 3
Rules
- Use
parseInt(value, 10)for integer parsing from the start of a string - Use
Number(value)for strict full-string conversion - Use
Number.isNaN(result)to detect invalid conversion - Use
Math.trunc()if you need to remove decimals after strict conversion
Common results
parseInt("42px", 10); // 42
Number("42px"); // NaN
parseInt("3.7", 10); // 3
Number();
();
(, );
FAQ
Should I use parseInt() or Number() in JavaScript?
Use Number() when the entire string must be numeric. Use parseInt() when you want to extract an integer from the beginning of a string.
Why does parseInt("10px", 10) return 10?
Because parseInt() reads from left to right and stops when it reaches a non-numeric character.
Why does Number("10px") return NaN?
Because Number() requires the whole string to be a valid number.
How do I check if conversion failed?
Use Number.isNaN(value).
const value = Number("abc");
console.log(Number.isNaN(value)); // true
Does parseInt() round decimal numbers?
Mini Project
Description
Build a small utility that converts user-provided text into an integer safely. This demonstrates how to handle valid numbers, decimal strings, empty input, and invalid characters in a practical way.
Goal
Create a function that accepts a string and returns a valid integer or a clear error message.
Requirements
- Write a function that accepts a string input
- Reject empty or whitespace-only input
- Convert valid numeric input to an integer
- Return an error message for invalid input
- Demonstrate the function with several test values
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.