Last modified: Jul 20, 2026

Convert String to Number in JavaScript

Working with data often means changing types. In JavaScript, you will frequently need to convert a string to a number variable. This is a core skill for any developer.

Strings and numbers behave differently. Adding a string to a number gives a string. This can break your code. Understanding conversion helps you avoid bugs.

This guide covers the main methods. You will learn Number(), parseInt(), parseFloat(), and the unary plus operator. Each method has a specific use case.

Why Convert a String to a Number?

User input from forms always comes as a string. For example, a user enters their age in a text box. That value is a string like "25". To do math, you need a number.

APIs and databases also return strings. A price might come as "$19.99" or "19.99". You must convert it before calculations. Without conversion, you get unexpected results.

Consider this example:

// Without conversion, this concatenates strings
let total = "10" + "20";
console.log(total); // Output: "1020"
"1020"

This is a common mistake. The plus operator works for both addition and concatenation. When one operand is a string, JavaScript converts the other to a string too.

Using the Number() Function

The Number() function is the simplest way. It converts the entire string to a number. It works with integers and floats.

If the string contains non-numeric characters, it returns NaN (Not a Number). This is useful for validation.

// Convert a simple integer string
let age = Number("25");
console.log(age); // Output: 25
console.log(typeof age); // Output: "number"

// Convert a float string
let price = Number("19.99");
console.log(price); // Output: 19.99

// Invalid string returns NaN
let invalid = Number("hello");
console.log(invalid); // Output: NaN
25
"number"
19.99
NaN

Important:Number() is strict. It does not ignore extra characters. A string like "25px" returns NaN. For such cases, use parseInt() or parseFloat().

Using parseInt() for Integers

The parseInt() function parses a string and returns an integer. It reads from left to right. It stops at the first non-numeric character.

This is great for strings like "100px" or "42 years". It ignores the trailing text. You can also specify a radix (base) for different number systems.

// Basic usage
let width = parseInt("100px");
console.log(width); // Output: 100

// With radix (base 10 is recommended)
let binary = parseInt("1010", 2);
console.log(binary); // Output: 10

// Invalid start returns NaN
let bad = parseInt("hello");
console.log(bad); // Output: NaN
100
10
NaN

Always specify the radix when using parseInt(). Without it, older browsers might interpret "08" as octal (base 8). This can lead to bugs. Use parseInt(string, 10) for decimal numbers.

Using parseFloat() for Floats

The parseFloat() function works like parseInt(), but it keeps decimal points. It is perfect for strings like "3.14" or "99.5%".

It also stops at the first invalid character. This makes it flexible for real-world data.

// Convert a percentage string
let percentage = parseFloat("85.5%");
console.log(percentage); // Output: 85.5

// Convert a measurement
let length = parseFloat("12.7cm");
console.log(length); // Output: 12.7

// Invalid input returns NaN
let invalidFloat = parseFloat("abc");
console.log(invalidFloat); // Output: NaN
85.5
12.7
NaN

parseFloat() only parses one decimal point. A string like "12.7.8" becomes 12.7. The rest is ignored. This is a useful behavior for cleaning data.

Using the Unary Plus Operator

The unary plus operator (+) is a shorthand. Placing a + before a string converts it to a number. It works the same as Number().

This method is concise and fast. However, it can reduce readability for beginners. Use it when you need quick inline conversion.

// Quick conversion with unary plus
let score = +"95";
console.log(score); // Output: 95

// Works with floats
let pi = +"3.14159";
console.log(pi); // Output: 3.14159

// Invalid returns NaN
let notNumber = +"test";
console.log(notNumber); // Output: NaN
95
3.14159
NaN

This operator is common in frameworks like React. You will see it in codebases for converting props. Just be careful with empty strings. +"" returns 0, which might be unexpected.

Comparison of Methods

Each method has strengths. Here is a quick summary:

  • Number() – Best for clean strings. Returns NaN on invalid input.
  • parseInt() – Best for strings with trailing text. Returns integer only.
  • parseFloat() – Best for strings with decimals and trailing text.
  • Unary plus (+) – Shortest syntax. Same behavior as Number().

Choose based on your data source. If you control the input, Number() is fine. For user input, parseInt() or parseFloat() are safer.

Common Pitfalls and Best Practices

Watch out for these common mistakes:

Empty strings:Number("") returns 0. This can cause silent errors. Always validate input before conversion.

Whitespace:Number(" 123 ") works, but Number("123 456") returns NaN. Trim strings first using .trim().

Null and undefined:Number(null) returns 0, while Number(undefined) returns NaN. Be explicit with checks.

Here is a safe conversion function:

// A safe conversion function
function safeConvert(str) {
  if (str === null || str === undefined) {
    return NaN;
  }
  let trimmed = str.trim();
  if (trimmed === "") {
    return NaN;
  }
  return Number(trimmed);
}

console.log(safeConvert("  42  ")); // Output: 42
console.log(safeConvert(""));       // Output: NaN
console.log(safeConvert(null));     // Output: NaN
42
NaN
NaN

Real-World Examples

Let's see conversion in action. Imagine you are building a calculator for a shopping cart.

// Shopping cart example
let priceStr = "29.99";
let quantityStr = "3";

// Convert strings to numbers
let price = parseFloat(priceStr);
let quantity = parseInt(quantityStr, 10);

// Calculate total
let total = price * quantity;
console.log("Total: $" + total.toFixed(2)); // Output: Total: $89.97
Total: $89.97

Another example is processing user age from a form:

// Form input conversion
let userInput = "25 years old";
let age = parseInt(userInput, 10);

if (!isNaN(age)) {
  console.log("User age is " + age); // Output: User age is 25
} else {
  console.log("Invalid age input");
}
User age is 25

Understanding JavaScript variable types is crucial here. A variable can change type after conversion. For more on this, see our JavaScript Variable Types Guide.

Performance Considerations

All these methods are fast. The unary plus is slightly faster than Number() in some engines. However, the difference is negligible for most apps.

Focus on readability first. Use Number() for clarity. Use parseInt() and parseFloat() for flexibility. The unary plus is good for short, inline code.

If you need to convert many values in a loop, consider using map() with Number:

// Convert an array of strings to numbers
let stringArray = ["1", "2", "3"];
let numberArray = stringArray.map(Number);
console.log(numberArray); // Output: [1, 2, 3]
[1, 2, 3]

This is clean and efficient. Remember that map(Number) will produce NaN for invalid strings. Handle that separately if needed.

Conclusion

Converting a string to a number in JavaScript is a fundamental task. You have several reliable methods: Number(), parseInt(), parseFloat(), and the unary plus operator.

Each method has its place. Number() is strict. parseInt() and parseFloat() are forgiving with trailing text. The unary plus is concise.

Always validate your input. Check for NaN using isNaN() or Number.isNaN(). This prevents silent errors in your application.

Practice these conversions. They will become second nature. For more on variable handling, check our JavaScript Variable Declaration Guide and JavaScript Variable Shadowing article.