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.
()。
()。
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 mentions 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.
var a = " 42";
var b = " 42mm";
var c = "0xff";
var d = "42.34";
(Number(a));//42
(Number(b));//NaN
(Number(c));//255
(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.
var b = " 42mm";
var c = "0xff";
var x = "-12.34";
var y = "15.88";
var z = "101010";
(parseInt(b));//42
(parseInt(x));//-12
(parseInt(y));//15
(parseInt(c));//255
(parseInt(z, 2));//42
(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.
var c = "0xff";
var d = "42.34";
(parseFloat(c));//0, because "0xff" start with 0
(parseFloat(d));//42.34
(parseFloat(".1"));//0.1