The Javascript Number.parseInt()
method parses a string argument to an integers by radix.
Number.parseInt(string,[ radix])
Parameter | Optional | Meaning |
---|---|---|
string | Required | The value to parse. |
radix | Optional | An integer between 2 and 36 that represents the radix |
It returns NaN:
Number.parseInt === parseInt // true
Number.parseInt()
understands two signs: + for positive, and - for negative.
Number.parseInt()
converts a BigInt to a Number and loses precision.
Using Number.parseInt()
.
console.log(Number.parseInt('0xF', 16)); console.log(Number.parseInt('F', 16)); console.log(Number.parseInt('17', 8)); console.log(Number.parseInt(021, 8)); console.log(Number.parseInt('015', 10) ); console.log(Number.parseInt(015, 10) ); console.log(Number.parseInt(15.99, 10));
Using parseInt()
.
console.log(Number.parseInt('15,123', 10)); console.log(Number.parseInt('F123', 16)); console.log(Number.parseInt('1111', 2)); console.log(Number.parseInt('15*3', 10)); console.log(Number.parseInt('15e2', 10)); console.log(Number.parseInt('15px', 10)); console.log(Number.parseInt('12', 13));
Using parseInt()
.
console.log(Number.parseInt('-F', 16)); console.log(Number.parseInt('-0F', 16)); console.log(Number.parseInt('-0XF', 16)); console.log(Number.parseInt(-15.1, 10)); console.log(Number.parseInt('-17', 8)); console.log(Number.parseInt('-15', 10)); console.log(Number.parseInt('-1111', 2)); console.log(Number.parseInt('-15e1', 10)); console.log(Number.parseInt('-12', 13));
The following examples all return NaN:
console.log(Number.parseInt('Hello', 8)); console.log(Number.parseInt('546', 2)); // Digits other than 0 or 1 are invalid for binary radix
BigInt values lose precision:
console.log(Number.parseInt('900719925474099267n'));