Skip to content

JavaScript Tutorial Numbers and Math

Converting to Numbers: parseInt, parseFloat and Number()

Lesson 37 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Values from forms, URLs and storage are strings. Before doing maths, convert them.

Number()

Converts the whole string, or gives NaN.

script.js
JS
console.log(Number("42"));      // → 42
console.log(Number("3.14"));    // → 3.14
console.log(Number("  7  "));   // → 7
console.log(Number(""));        // → 0
console.log(Number("12px"));    // → NaN
console.log(Number("abc"));     // → NaN

Note that an empty string becomes 0, which can hide a problem.

parseInt

Reads whole numbers from the start of the text and stops at the first invalid character.

script.js
JS
console.log(parseInt("42px"));    // → 42
console.log(parseInt("3.99"));    // → 3
console.log(parseInt("px42"));    // → NaN
console.log(parseInt("101", 2));  // → 5

The second argument is the radix (the number base). Always pass 10 when parsing decimal text, to be explicit: parseInt("08", 10).

parseFloat

Same idea, but it keeps decimals.

script.js
JS
console.log(parseFloat("3.14abc")); // → 3.14
console.log(parseFloat(".5"));      // → 0.5
console.log(parseFloat("abc"));     // → NaN

Which one?

SituationUse
The whole string must be a numberNumber()
Text like "20px" or "15%"parseFloat() or parseInt(x, 10)
Whole numbers onlyparseInt(x, 10)

Always check the result

script.js
JS
function readAge(text) {
  const age = Number(text);
  if (text.trim() === "" || Number.isNaN(age)) {
    return null;
  }
  return age;
}

console.log(readAge("25"));  // → 25
console.log(readAge("abc")); // → null
console.log(readAge(""));    // → null

The unary plus shortcut

+"42" also converts to a number. It works like Number(), but Number() is clearer to read.

warning
Forgetting that inputs are strings
input.value + 1 joins text: "5" + 1 is "51". Convert first: Number(input.value) + 1. You will use this in the calculator project.