JavaScript String to Number Conversion: Practical Guide

A practical guide to converting strings to numbers in JavaScript, covering Number(), parseInt/parseFloat, unary plus, NaN handling, and input validation with real-world examples.

JavaScripting
JavaScripting Team
·5 min read
String to Number in JS - JavaScripting
Quick AnswerSteps

In JavaScript, converting a string to a number can be done with multiple approaches. Use the unary plus operator (+value) for quick conversion, or wrap the string with Number(value). For integers, parseInt(value, 10) works; for decimals, parseFloat(value) is suitable. Be mindful of NaN results and trimming whitespace.

Understanding javascript conversion string to number in practice

Converting strings to numbers is a fundamental task when parsing data from APIs, forms, or CSVs. The concept of javascript conversion string to number encompasses coercion rules, string trimming, and numeric parsing strategies. In JavaScript, numbers are stored as double-precision floating-point values, which means string inputs must be parsed to yield meaningful numbers. The choice between Number(), parseInt, parseFloat, and the unary plus operator depends on the expected input (integer vs decimal) and the tolerance for non-numeric characters. In addition, you must handle invalid input gracefully to avoid runtime errors and to provide helpful feedback to users.

JavaScript
// 1) Unary plus const s1 = "42"; const n1 = +s1; // 42 // 2) Number() const s2 = "3.14"; const n2 = Number(s2); // 3.14 // 3) parseInt / parseFloat console.log(parseInt("101", 10)); // 101 console.log(parseFloat("7.5")); // 7.5
  • Unary plus is concise for simple integers or decimals.
  • Number() is explicit and can be clearer in code review.
  • parseInt/parseFloat handle parsing with base control and decimal handling.
  • Always trim and validate inputs when parsing from untrusted sources.

Steps

Estimated time: 20-35 minutes

  1. 1

    Identify input source

    Determine where the string comes from (user input, API, file). Normalize by trimming and checking type before conversion.

    Tip: Always trim input to avoid hidden whitespace issues.
  2. 2

    Choose conversion method

    If you expect integers use parseInt with radix 10; for decimals use parseFloat or Number depending on clarity.

    Tip: Prefer a single clear method in code reviews.
  3. 3

    Validate result

    Check that the result is finite and not NaN before using it in calculations.

    Tip: Use Number.isFinite(n) or Number.isNaN(value) for robust checks.
  4. 4

    Handle edge cases

    Define behavior for empty strings, null, undefined, or non-numeric values (e.g., defaulting to 0 or returning null).

    Tip: Document your fallback policy for downstream code.
Pro Tip: Prefer Number.isFinite over global isFinite for predictable results.
Warning: Be cautious with NaN; NaN !== NaN, so use Number.isNaN to detect NaN.
Note: Trim input before conversion to avoid accidental parsing failures.

Prerequisites

Required

Commands

ActionCommand
Evaluate a numeric string in NodeQuick check of Number() on a literal stringnode -e 'console.log(Number("42"))'
Parse integer from stringBase-10 integer parsingnode -e 'console.log(parseInt("101", 10))'
Parse float from stringParses decimal numbersnode -e 'console.log(parseFloat("7.5"))'

Questions & Answers

What is the difference between Number(), parseInt(), and parseFloat() in JavaScript?

Number() converts a string to a number (integer or float) and returns NaN if invalid. parseInt() parses an integer with an optional radix, while parseFloat() parses a floating-point number. They differ in handling non-numeric trailing characters and in what they return for invalid input.

Number() tries to convert the whole string; parseInt and parseFloat read up to the first non-numeric character, returning a number or NaN if nothing valid is found.

How do I safely detect NaN results after conversion?

Use Number.isNaN(value) to reliably detect NaN. Do not use value !== value, which can be less readable. Also consider Number.isFinite to guard against Infinity.

Check with Number.isNaN or Number.isFinite to ensure your code handles non-numeric values safely.

What happens if the string is empty or contains only spaces?

Number('') returns 0 and parseInt('') returns NaN. Trim whitespace first, then convert, to avoid surprises in your logic.

An empty string becomes zero with Number(), so trim first or test for emptiness.

Can I convert boolean values to numbers?

Number(true) yields 1 and Number(false) yields 0. This is often useful when encoding boolean flags as numbers.

True becomes one, false becomes zero when you convert booleans to numbers.

Is there a safe pattern for converting user input from forms?

Trim the string, use Number() or parseFloat, and verify with Number.isFinite(result). Provide a fallback if conversion fails.

Trim, convert, and verify the result to avoid bad data from forms.

What to Remember

  • Use unary + or Number() for concise conversion
  • ParseInt/parseFloat offer control over base and decimals
  • Always validate and sanitize input to avoid NaN or Infinity
  • Be explicit about edge cases (empty, null, non-numeric)

Related Articles