Course contentsShow
← JavaScript
Lesson 104 of 2,7234. Working with NumbersFree lesson

Number.parseInt and Number.parseFloat

Parse strings into integers or floating-point numbers, handling radix and stopping at non-numeric characters.

Number.parseInt and Number.parseFloat

You'll learn how to extract numbers from strings, even when they contain extra text or characters.

What Are parseInt and parseFloat?

Sometimes you receive data as strings — like "42" or "3.14" — but need to perform math on them. Number.parseInt and Number.parseFloat convert strings into actual numbers, stopping when they hit characters that can't be part of a number.

Think of it like reading a price tag: if you see "$19.99 each", you naturally extract the number and ignore the rest.

Number.parseInt

Number.parseInt(string, radix) reads a string from left to right and returns an integer:

Number.parseInt("42");        // 42
Number.parseInt("42.99");     // 42 (stops at the decimal)
Number.parseInt("100px");     // 100 (ignores "px")
Number.parseInt("  25  ");    // 25 (ignores whitespace)
Number.parseInt("no123");     // NaN (can't start with letters)

The radix (optional, but recommended) specifies the number system — 10 for decimal, 16 for hexadecimal, 2 for binary:

Number.parseInt("1010", 2);   // 10 (binary to decimal)
Number.parseInt("FF", 16);    // 255 (hexadecimal)
Number.parseInt("42", 10);    // 42 (decimal, explicit)

Number.parseFloat

Number.parseFloat(string) works similarly but preserves decimals:

Number.parseFloat("3.14");       // 3.14
Number.parseFloat("2.5rem");     // 2.5 (stops at "r")
Number.parseFloat("  1.99  ");   // 1.99

Unlike parseInt, parseFloat doesn't take a radix — it always assumes decimal.

When They Return NaN

Both return NaN if the string doesn't start with a valid number (after trimming whitespace).

Key Takeaway: Use Number.parseInt to extract integers from strings (with an optional radix), and Number.parseFloat for decimals — both stop parsing at the first non-numeric character.