In JavaScript, you can convert the string value into a number in the following three ways:
1. Call Number() to convert the value type of string.
2.parseInt().
3.parseFloat().
Number()
Using the Number() function to cast a string is the most straightforward way. However, this approach has one limitation: if the string cuts off the beginning and ending whitespace characters and is not a pure numeric string, the final result is NaN. David Flanagan's JavaScript The Definitive Guide 6th edition, Section 3.8.2 mentioned that when using the Number() function to perform 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 into a numerical value of 255.
The code copy is as follows:
var a = " 42";
var b = " 42mm";
var c = "0xff";
var d = "42.34";
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-digit partial 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 rounding is "truncate".
In addition to string as the first parameter, the parseInt() function can also accept any integer between 2 and 36 as the second parameter to specify the number of divisions during the conversion process.
The code copy is as follows:
var b = " 42mm";
var c = "0xff";
var x = "-12.34";
var y = "15.88";
var z = "101010";
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 partial numeric strings starting with numbers (non-numeric partial strings 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 process decimal strings.
The code copy is as follows:
var c = "0xff";
var d = "42.34";
console.log(parseFloat(c));//0, because "0xff" start with 0
console.log(parseFloat(d));//42.34
console.log(parseFloat(".1"));//0.1