Convert string to a number

JavaScript's standard built-in functions parseInt, parseFloat and Number can be used to convert a string to numbers.

Convert a string to integer using parseInt

The second parameter passed to parseInt defines the base of the number. For example, you would pass 16 in case of converting a string in base-16 format to number.

// this is a base 10 number
parseInt("12", 10); // 12

// converting from base 16 format
parseInt("b", 16); // 11
parseInt("0xb", 16); // 11

// In case of an error, it returns a `NaN`
const num = parseInt("hello", 10); // NaN
isNaN(num); // true

Convert to floating point numer using parseFloat

parseFloat("12.45"); // 12.45

Using the Number function

Number("12.78"); // 12.78
Number("67"); // 67
Number("js"); // NaN

// Hexadecimal numbers start with `0x`
Number("0xb"); // 11
Number("0b11"); // 3
Number("0o10"); // 8
Last updated on Thu Jan 07 2021