The Javascript parseInt()
function parses a string to an integer.
We can specify radix, which is the base in mathematical numeral systems.
parseInt(string [, radix])
Parameters | Optional | Meaning |
---|---|---|
string | Not | The value to parse. |
radix | Optional | An integer between 2 and 36 that represents the radix |
parseInt()
return NaN when
parseInt()
understands two signs: + for positive, and - for negative.
parseInt()
converts a BigInt to a Number and loses precision.
Using parseInt()
.
console.log(parseInt('0xF', 16)); console.log(parseInt('F', 16)); console.log(parseInt('17', 8)); console.log(parseInt(021, 8));/*from w w w. j a va 2 s .c om*/ console.log(parseInt('015', 10) ); console.log(parseInt(015, 10) ); console.log(parseInt(15.99, 10));
Using parseInt()
.
console.log(parseInt('15,123', 10)); console.log(parseInt('F123', 16)); console.log(parseInt('1111', 2)); console.log(parseInt('15*3', 10)); console.log(parseInt('15e2', 10)); console.log(parseInt('15px', 10)); console.log(parseInt('12', 13));
Using parseInt()
.
console.log(parseInt('-F', 16)); console.log(parseInt('-0F', 16)); console.log(parseInt('-0XF', 16)); console.log(parseInt(-15.1, 10)); console.log(parseInt('-17', 8)); console.log(parseInt('-15', 10)); console.log(parseInt('-1111', 2)); console.log(parseInt('-15e1', 10)); console.log(parseInt('-12', 13));
The following examples all return NaN:
console.log(parseInt('Hello', 8)); console.log(parseInt('546', 2)); // Digits other than 0 or 1 are invalid for binary radix
BigInt values lose precision:
console.log(parseInt('900719925474099267n'));