Question

How to Convert a String to an Integer in JavaScript

javascriptstringintegerdata-conversion

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 like Number().

So if the paper says:

  • "42" → all methods can understand it
  • "42px" → parseInt() reads 42, but Number() rejects it
  • "3.9" → Number() reads 3.9, while parseInt() keeps only the integer part 3

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
Take Quiz

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 = decimal
  • 2 = binary
  • 16 = 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:

const value = "123.99";
const result = Math.trunc(Number(value));

console.log(result); // 123

Using unary plus

const value = "456";
const result = +value;

console.log(result); // 456

This is concise, but some beginners find Number() easier to read.

Example comparison

console.log(parseInt("42", 10));   // 42
console.log(Number("42"));         // 42
console.log(+"42");                // 42

console.log(parseInt("42px", 10)); // 42
console.log(Number("42px"));       // NaN

console.log(parseInt("3.7", 10));  // 3
console.log(Number("3.7"));        // 3.7

Explanation

  • parseInt("42px", 10) works because it stops reading when it reaches p
  • Number("42px") fails because the whole string is not a valid number
  • parseInt("3.7", 10) returns 3 because it reads only the integer part before the decimal point

Step by Step Execution

Consider this example:

const input = "15px";
const result = parseInt(input, 10);
console.log(result);

Step by step:

  1. input stores the string "15px"
  2. parseInt(input, 10) begins reading from the start of the string
  3. It sees 1, which is valid in base 10
  4. It sees 5, which is also valid in base 10
  5. It sees p, which is not valid in a decimal integer
  6. It stops reading at that point
  7. It returns the integer 15
  8. console.log(result) prints 15

Now compare with Number():

const input = "15px";
const result = Number(input);
console.log(result);

Step by step:

  1. input stores "15px"
  2. Number(input) checks whether the entire string is a valid number
  3. "15px" is not a valid numeric string
  4. JavaScript returns NaN
  5. console.log(result) prints NaN

One more example with whitespace:

const input = "   27   ";
console.log(Number(input));      // 27
console.log(parseInt(input, 10)); // 27

Both methods can handle surrounding whitespace.

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);

Command-line scripts

Arguments are usually strings.

const port = "3000";
const portNumber = Number(port);
Take Quiz

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.

const rawPort = process.env.PORT || "3000";
const port = Number(rawPort);

if (Number.isNaN(port)) {
  throw new Error("PORT must be a number");
}

Converting arrays of numeric strings

const values = ["1", "2", "3"];
const numbers = values.map(Number);

console.log(numbers); // [1, 2, 3]

Early return pattern

function parsePage(pageInput) {
  const page = Number(pageInput);

  if (Number.isNaN(page) || page < 1) {
    return 1;
  }

  return Math.trunc(page);
}

In production code, the main concern is not just conversion. It is safe conversion.

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:

parseInt("42", 10);

This makes your intent clear and avoids confusion.

4. Not checking for NaN

Broken approach:

const value = Number("hello");
if (value === NaN) {
  console.log("Invalid");
}

This does not work because NaN is never equal to itself.

Fix

const value = Number("hello");
if (Number.isNaN(value)) {
  console.log("Invalid");
}

5. Assuming parseInt() rounds decimals

parseInt("3.9", 10); // 3

This is not rounding. It stops before the decimal part.

If you want rounding:

Math.round(Number("3.9")); // 4

6. Confusing empty strings with invalid numbers

Number(""); // 0

This surprises many beginners. If empty input should be invalid, check for it before conversion.

const input = "";
if (input.trim() === "") {
  console.log("Input is empty");
}

Comparisons

MethodExampleResult with "42"Result with "42px"Result with "3.9"Best use
parseInt(value, 10)parseInt("42", 10)42423Extracting an integer from the start of a string
Number(value)Number("42")42NaN3.9Strict full-string numeric conversion
Unary plus+"42"42NaN3.9Short form of Number()
Math.trunc(Number(value))Math.trunc(Number("3.9"))42NaN3Strict conversion followed by integer truncation

parseInt() vs Number()

  • Use parseInt() when the string may start with a number and then contain extra characters
  • Use Number() when the entire string must be a valid number

Number() vs unary plus

  • They behave almost the same for string conversion
  • Number() is usually easier for beginners to read
  • Unary plus is shorter but less explicit
Take Quiz

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("3.7");        // 3.7

Number("");           // 0
parseInt("", 10);     // NaN

Safe pattern

const input = "25";
const num = Number(input);

if (input.trim() === "" || Number.isNaN(num)) {
  console.log("Invalid input");
} else {
  console.log(num);
}

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?

No. It stops reading at the decimal point.

parseInt("4.9", 10); // 4

Why does Number("") return 0?

JavaScript treats an empty string as zero in numeric conversion. If that is not desired, check for empty input before converting.

Can I convert an array of numeric strings to numbers?

Yes.

const values = ["1", "2", "3"];
const numbers = values.map(Number);

What is the safest beginner-friendly approach?

Use Number() and then validate with Number.isNaN(). If you need a whole integer only, apply Math.trunc() or validate that the input is an integer.

Take Quiz

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
Take Quiz

Keep learning

Related questions

View more