在Javascript中引入字符串到数字

在Javascript中,字符串值可以通过以下3种方法转换成数字:



1。调用数字()将值类型转换为字符串。

2.parseint()。

3.parsefloat()。



数()



Using the Number () function to enforce a forced type conversion of string is the most direct approach.However, this approach has a limitation: if the string at the beginning and end of the cut blank characters, not pure digital string, then return the result to NaN.David Flanagan Javascript - The Definitive Guide 6th Edition, 3.8.2 Number) (mentioned in the section, to carry out string-to-number conversion function, the function only accepts 10 hexadecimal string, but the test results show that this is not the case, the Number () function can accept 0xff as a parameter and convert it to a value of 255.



复制代码代码如下所示:

var42;

var b =42mm ;

var c = 0xFF;

var a 42.34 ;

console.log(编号(一)); / / 42

console.log(数(B)); / /南

console.log(数(C)); / / 255

console.log(数(D)); / / 42.34





ParseInt()



ParseInt()函数可以将字符串转换为整数,和数量()parseInt()函数,函数不仅可以解析纯数字的字符串也可以解决在数字的数字字符串的一部分开始(非数字字符串的一部分将在转换过程中去除)。值得注意的是,当parseInt()函数分析浮点数字的字符串,用于向下取整整数运算方法(截断)。



除了字符串作为第一个参数,在parseInt()函数也接受2到36之间的任意整数作为第二个参数,用于指定在转型过程中的基数。



复制代码代码如下所示:

var b =42mm ;

var c = 0xFF;

var = 12.34;

15.88;

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)); / /南





ParseFloat()



像parseInt(),parseFloat()也可以解析多个数字字符串开头号码(非数字字符串转换过程中移除)。不像parseInt(),可以将字符串转换为parseFloat()浮点数,但parseFloat()只接受一个参数只能处理10位二进制字符串。



复制代码代码如下所示:

var c = 0xFF;

var42.34;

console.log(parseFloat(C)); / / 0,因为0xFF开始0

console.log(parseFloat(d)); / / 42.34

console.log(parseFloat(1)); / / 0.1