In JavaScript, you can convert a string value to number in 3 ways:
1. Call number () to convert the string to a value type.
2.parseInt ().
3.parseFloat ().
Number ()
It is most straightforward to use the number () function to force type conversions on a string. However, this practice has a limitation: if the string is truncated to the first and the trailing white space character, and is not a pure numeric string, the result is Nan. David Flanagan's javascript–the Definitive Guide 6th edition, 3.8.2 mentions that when you use the number () function to perform a string-to-number conversion, the function accepts only 10 strings, But the test results indicate that this is not the case, and the number () function can accept "0xFF" as a parameter and convert it to a value of 255.
Copy Code code 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 converts a string to an integer, compared to the number () function, the parseint () function can parse not only a pure numeric string, but also a partial numeric string that begins with a number (a non-numeric part string is removed during conversion). It is worth noting that when the parseint () function resolves a floating-point number string, the method used by the rounding operation is "rounding down" (truncate).
In addition to the string as the first argument, the parseint () function can also accept any integer from 2 to 36 as the second argument that specifies the number of numbers in the conversion process.
Copy Code code 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 ()
As with parseint (), parsefloat () can also resolve partial numeric strings that begin with a number (non-numeric part strings are removed during conversion). Unlike parseint (), parsefloat () can convert a string to a floating-point number, but at the same time, parsefloat () accepts only one parameter and can handle only a 10-character string.
Copy Code code 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