How to Convert Strings to Numbers in JavaScript: Number(), parseInt(), parseFloat(), and Best Practices

1. Introduction

JavaScript is one of the most widely used programming languages in web development. Among its many features, converting strings to numbers is a fundamental operation that is frequently required in real-world applications.

For example, values entered by users in forms or data retrieved from APIs are often treated as strings. These values cannot be used directly for calculations or comparisons unless they are converted into numeric types.

In this article, we will explain concrete methods for converting strings to numbers in JavaScript. We will cover how each function and technique works, their differences, and important points to keep in mind. Use this guide as a practical reference.

2. Overview of Data Types in JavaScript

JavaScript is known as a dynamically typed language, meaning that the type of a variable is determined automatically during program execution. While this provides flexibility, it can also lead to errors or unexpected behavior if type conversion is not handled carefully.

Main Data Types

JavaScript data types can be broadly divided into the following two categories.

  1. Primitive Types
  • Number: Represents integers and floating-point numbers.
  • String: Represents text data.
  • Boolean: Has only true or false.
  • Undefined: Indicates that a value has not been assigned.
  • Null: Explicitly represents the absence of a value.
  • Symbol: Used as a unique identifier.
  1. Object Types
  • Includes arrays (Array), functions (Function), dates (Date), and more.

Dynamic Typing and Type Conversion Pitfalls

In JavaScript, variable types may be converted implicitly or explicitly. Special attention is required when dealing with strings and numbers.

Example:

console.log("10" + 5); // Output: "105" (string concatenation)
console.log("10" - 5); // Output: 5 (numeric calculation)

As shown above, the same operator can behave differently depending on context. Explicit type conversion is essential to prevent unintended results.

3. Methods for Converting Strings to Numbers

JavaScript provides several ways to convert strings into numbers. This section explains four commonly used methods in detail.

The Number() Function

The Number() function is the most basic way to convert a string into a number.

Examples:

console.log(Number("42"));    // Output: 42
console.log(Number("3.14"));  // Output: 3.14
console.log(Number(""));      // Output: 0 (empty string becomes 0)
console.log(Number("abc"));   // Output: NaN (returns NaN if conversion fails)

Characteristics:

  • Converts both integers and floating-point numbers.
  • An empty string is converted to 0.
  • Returns NaN (Not-a-Number) if conversion fails.

Important Note:
NaN is a special numeric value that cannot be used in calculations. Using it unintentionally can lead to unexpected behavior.

The parseInt() Function

The parseInt() function converts a string into an integer. It parses the string from the beginning and stops at the first non-numeric character.

Examples:

console.log(parseInt("42"));         // Output: 42
console.log(parseInt("42.99"));      // Output: 42 (decimal part is ignored)
console.log(parseInt("10abc"));      // Output: 10
console.log(parseInt("abc10"));      // Output: NaN

Specifying the Radix:

console.log(parseInt("10", 2)); // Output: 2 (binary)
console.log(parseInt("A", 16)); // Output: 10 (hexadecimal)

Characteristics:

  • Useful when only the integer part is required.
  • Supports conversion from different numeral systems.

Caution:
If the radix is omitted, the result may depend on the string format, potentially causing unexpected results.

The parseFloat() Function

The parseFloat() function converts a string into a floating-point number.

Examples:

console.log(parseFloat("3.14"));     // Output: 3.14
console.log(parseFloat("3.14abc"));  // Output: 3.14
console.log(parseFloat("abc3.14"));  // Output: NaN

Characteristics:

  • Ideal for handling decimal values.
  • Works correctly for integer values as well.

Caution:

  • Like parseInt(), it ignores characters after the numeric portion.

The Unary Plus Operator (+)

The unary plus operator (+) provides a short and simple way to perform type conversion.

Examples:

console.log(+"42");      // Output: 42
console.log(+"3.14");    // Output: 3.14
console.log(+"abc");     // Output: NaN

Characteristics:

  • Produces concise code.
  • Behaves the same as Number().

Caution:
While concise, this approach may reduce readability. For beginner-friendly or team codebases, Number() is often clearer.

Summary

MethodCharacteristicsExample
Number()General-purpose conversion for integers and decimalsNumber("3.14") → 3.14
parseInt()Converts integers only, supports radixparseInt("42.99") → 42
parseFloat()Best for decimal valuesparseFloat("3.14") → 3.14
Unary +Concise but less explicit+"42" → 42

The next section explains the differences between these methods and how to choose the right one.

4. Differences Between Conversion Methods and How to Choose

JavaScript offers multiple ways to convert strings to numbers, each with distinct behavior. Understanding these differences is essential for selecting the correct method.

Number() vs parseInt()

Number() evaluates the entire string as a numeric value, while parseInt() extracts only the integer portion.

Example:

console.log(Number("42.5"));     // Output: 42.5
console.log(parseInt("42.5"));  // Output: 42

Usage Guidelines:

  • Use Number() when precise numeric values are required.
  • Use parseInt() when decimals should be ignored.

parseInt() vs parseFloat()

parseInt() is limited to integers, while parseFloat() handles decimal values.

Example:

console.log(parseInt("42.75"));     // Output: 42
console.log(parseFloat("42.75"));  // Output: 42.75

Usage Guidelines:

  • Use parseInt() for whole numbers such as ages or IDs.
  • Use parseFloat() for prices or measurements.

Number() vs Unary Plus (+)

Both Number() and the unary plus operator behave similarly, but readability differs.

Example:

console.log(Number("42"));  // Output: 42
console.log(+"42");         // Output: 42

Usage Guidelines:

  • Number() clearly expresses intent and is recommended for team projects.
  • The unary plus operator is useful when brevity is preferred.

Handling Special Cases

Empty Strings and Invalid Values

Example:

console.log(Number(""));           // Output: 0
console.log(parseInt(""));         // Output: NaN
console.log(+"");                  // Output: 0
console.log(Number("abc"));        // Output: NaN
console.log(parseFloat("abc123")); // Output: NaN

Key Points:

  • Use Number() or unary + when empty strings should become 0.
  • Be cautious with parseInt() and parseFloat(), as partial parsing may occur.

Summary

MethodMain Use CaseCharacteristicsExample
Number()General numeric conversionConverts entire string; invalid values become NaNNumber("3.14") → 3.14
parseInt()Integer-only valuesIgnores decimals and invalid suffixesparseInt("42.99") → 42
parseFloat()Decimal valuesHandles floating-point numbersparseFloat("3.14") → 3.14
Unary +Concise conversionEquivalent to Number(), less explicit+"42" → 42

5. Error Handling During Conversion

Proper error handling is essential when converting strings to numbers, especially when dealing with user input or external data.

Handling NaN (Not-a-Number)

When conversion fails, JavaScript returns NaN, which is technically a number type but cannot be used in calculations.

Example:

console.log(Number("abc"));      // Output: NaN
console.log(parseInt("xyz"));    // Output: NaN
console.log(+"test");            // Output: NaN

Key Points:

  • Any calculation involving NaN results in NaN.
  • NaN === NaN returns false.

Using isNaN()

The isNaN() function checks whether a value is NaN.

Example:

console.log(isNaN("abc")); // true
console.log(isNaN(42));    // false
console.log(isNaN(NaN));   // true

Caution:
isNaN() performs implicit type conversion.

Using Number.isNaN()

Number.isNaN() performs a strict check without type conversion.

Example:

console.log(Number.isNaN("abc"));      // false
console.log(Number.isNaN(NaN));        // true
console.log(Number.isNaN(undefined));  // false

Recommendation:

  • Use Number.isNaN() for reliable error checking.

Example: Handling Invalid Input

function safeConvert(input) {
  let value = Number(input);
  return Number.isNaN(value) ? 0 : value;
}

6. Practical Examples

This section presents real-world use cases, including user input, arrays, forms, and JSON data.

1. Converting User Input

function processUserInput(input) {
  let value = Number(input);

  if (Number.isNaN(value)) {
    console.log("Error: Please enter a number.");
    return null;
  }

  console.log("Entered value: " + value);
  return value;
}

2. Converting String Values in Arrays

let data = ["10", "20", "30", "40"];
let numbers = data.map(Number);
console.log(numbers);

3. Processing Form Data

function calculateTotalPrice(priceInput, quantityInput) {
  let price = parseFloat(priceInput);
  let quantity = parseInt(quantityInput);

  if (Number.isNaN(price) || Number.isNaN(quantity)) {
    console.log("Error: Please enter valid numbers.");
    return null;
  }

  let total = price * quantity;
  console.log("Total price: " + total);
  return total;
}

4. Converting JSON Data

let jsonData = '[{"id": "1", "price": "120.5"}, {"id": "2", "price": "200"}]';
let products = JSON.parse(jsonData);

let total = products.reduce((sum, product) => {
  let price = Number(product.price);
  return sum + (Number.isNaN(price) ? 0 : price);
}, 0);

console.log("Total price: " + total);

7. Conclusion

In this article, we covered string-to-number conversion in JavaScript from fundamentals to advanced use cases.

Key takeaways include understanding data types, choosing the right conversion method, and implementing proper error handling.

String-to-number conversion is a basic yet essential skill for real-world JavaScript development. Practice the examples provided here and apply them to your own projects to improve reliability and accuracy.

広告