Home > Article > Web Front-end > Introduction to converting string to number in JavaScript_javascript skills
In JavaScript, you can convert string values into numbers through the following 3 methods:
1. Call Number() to perform value type conversion on string.
2.parseInt().
3.parseFloat().
Number()
Using the Number() function to cast string is the most direct way. However, this approach has a limitation: if the string is not a pure numeric string after truncating the leading and trailing whitespace characters, the final return result will be NaN. David Flanagan's JavaScript - The Definitive Guide 6th edition, Section 3.8.2 mentioned that when using the Number() function for string-to-number conversion, the function only accepts decimal strings, but the test results show that this is not the case. The Number() function can accept "0xff" as a parameter and convert it to the value 255.
console.log(Number(a));//42
console.log(Number(b));//NaN
console.log(Number(c));//255
console.log(Number(d));//42.34
parseInt()
The parseInt() function can convert a string into an integer. Compared with the Number() function, the parseInt() function can not only parse pure numeric strings, but also parse partial numeric strings starting with numbers (non-digits). Some strings will be removed during the conversion process). It is worth noting that when the parseInt() function parses a floating-point string, the method used for the rounding operation is "truncate".
In addition to the string as the first parameter, the parseInt() function can also accept any integer between 2 and 36 as the second parameter, which is used to specify the base number during the conversion process.
console.log(parseInt(b));//42
console.log(parseInt(x));//-12
console.log(parseInt(y));//15
console.log(parseInt(c));//255
console.log(parseInt(z, 2));//42
console.log(parseInt(".1"));//NaN
parseFloat()
Like parseInt(), parseFloat() can also parse part of the numeric string starting with a number (the non-numeric part of the string will be removed during the conversion process). Unlike parseInt(), parseFloat() can convert a string into a floating point number; but at the same time, parseFloat() only accepts one parameter and can only handle decimal strings.
console.log(parseFloat(c));//0, because "0xff" start with 0
console.log(parseFloat(d));//42.34
console.log(parseFloat(".1"));//0.1