AD JB Toolbox 01 EN

JavaScript Number(): Convert Strings and Validate Input

Number(value) converts a JavaScript value, including a numeric string, to a number. If the entire string cannot be interpreted as a number, the result is NaN. Empty strings and strings containing only whitespace become 0, so validate missing input before converting.

Conversion results and surprising inputs

Number("12")      // 12
Number("12.5")    // 12.5
Number(" 12 ")    // 12
Number("12px")    // NaN
Number("1,000")   // NaN
Number("")        // 0
Input Result What to check
"1e3" 1000 Exponent notation is accepted
"0x10" 16 Hexadecimal notation is accepted
"Infinity" Infinity A number, but not a finite value
null 0 Distinguish a missing value from zero
undefined NaN Cannot be converted to a valid number

NaN means "Not a Number", but typeof NaN still returns "number". Use Number.isNaN() to detect NaN, or Number.isFinite() when NaN and positive or negative infinity should all be rejected. See Number() conversion rules and Number.isFinite() for their different roles.

Complete example: reject blank input first

Save the example as number-example.html in UTF-8 and open it in a browser. It trims leading and trailing whitespace, rejects an empty value, converts the remaining text, and checks that the result is finite.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Number() input validation</title>
  <style>
    body { margin: 24px; font: 16px/1.7 sans-serif; }
    input, button, select { font: inherit; max-width: 100%; }
    label { display: block; margin-top: 12px; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
<label for="value">String to convert</label>
<input id="value" type="text" value="12.5">
<button id="convert" type="button">Convert to number</button>
  <pre id="output" aria-live="polite"></pre>
  <script>
    function convert() {
      const text = document.getElementById("value").value.trim();
      const output = document.getElementById("output");
      if (text === "") {
        output.textContent = "Enter a value.";
        return;
      }
      const number = Number(text);
      if (!Number.isFinite(number)) {
        output.textContent = "Cannot convert to a finite number.";
        return;
      }
      output.textContent = `Value: ${number} / Type: ${typeof number} / After adding 2: ${number + 2}`;
    }
    document.getElementById("convert").addEventListener("click", convert);
    convert();
  </script>
</body>
</html>

The initial result is Value: 12.5 / Type: number / After adding 2: 14.5. Whitespace produces an input prompt; 12px and Infinity produce a conversion error. Try 0 as well: it must remain a valid number. The expression "1" + "2" returns "12", while adding Number("1") and Number("2") returns 3.

Number(), parseInt() and parseFloat()

Number("12.5px")       // NaN
parseInt("12.5px", 10)  // 12
parseFloat("12.5px")    // 12.5

Number("12.5")         // 12.5
parseInt("12.5", 10)    // 12

parseInt() and parseFloat() read a numeric prefix and stop when they reach an unsupported character. That can be useful when extracting the numeric part of a CSS value, but it does not validate an entire user input. Specify the radix when appropriate, such as parseInt(text, 10) for base 10. The parseFloat() documentation describes how this differs from Number().

Check the accepted format and precision

  • Number() accepts hexadecimal and exponent notation. If your form permits only ordinary decimal notation, enforce that format before conversion.
  • For input such as "1,000", validate comma positions before removing separators. Deleting every nonnumeric character can silently alter invalid data.
  • Number.isSafeInteger() checks whether an integer is within the safe range. A large integer may already lose digits when converted to Number, so retain the original string if exact digits matter.
  • Avoid new Number() for conversion: it creates a wrapper object rather than a primitive number.
More in This Category
JavaScript Loops: while, do...while and for Compared

JavaScript Loops: while, do...while and for Compared

Compare loop execution order and behavior when the initial condition is false. Learn how break and continue work and avoid infinite loops and index boundary errors.

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

Compare rounding methods for positive and negative values, round at different positions, and distinguish floating-point arithmetic from toFixed() display formatting.

JavaScript String(): Convert Numbers to Strings

JavaScript String(): Convert Numbers to Strings

Learn how String() converts values, why string concatenation differs from addition, and when null handling or JSON serialization is needed. Compare primitive strings with new String() objects.

JavaScript Conditionals: if, else if, else and switch

JavaScript Conditionals: if, else if, else and switch

Choose conditional branches with if and switch, understand strict matching and fall-through, and validate input before comparing numbers. Includes a complete browser example.

JavaScript Notes: Number Formatting, URI Encoding and Selectors

JavaScript Notes: Number Formatting, URI Encoding and Selectors

Format numbers, choose the right URI encoding function, and build query parameters safely. Includes decoding error handling, CSS selector guidance and a runnable URL example.

JavaScript Number(): Convert Strings and Validate Input

JavaScript Number(): Convert Strings and Validate Input

Convert text to numbers while rejecting blank and nonfinite input. Compare Number(), parseInt() and parseFloat(), and account for accepted formats and precision limits.

JavaScript Thousands Separators: Add Commas and Parse Input

JavaScript Thousands Separators: Add Commas and Parse Input

Format numbers with locale-aware thousands separators and validate grouped decimal input before converting it. Covers decimal options, string formatting and precision limits.