Home >Web Front-end >Front-end Q&A >How to convert string to number in es6
Conversion method: 1. Use parseInt() to convert the string to an integer, the syntax "parseInt("string")"; 2. Use parseFloat() to convert the string to a floating point number, the syntax "parseFloat ("string")"; 3. Use the multiplication operator, the syntax is "numeric string * 1".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Method 1: Use parseInt() to convert to an integer
console.log(parseInt("12345red")); //返回 12345 console.log(parseInt("0xA")); //返回 10 console.log(parseInt("56.9")); //返回 56 console.log(parseInt("red")); //返回 NaN console.log(parseInt("AF", 16)); //返回 175 console.log(parseInt("10", 2)); //返回 2 console.log(parseInt("10", 8)); //返回 8 console.log(parseInt("10", 10)); //返回 10 //如果十进制数包含前导 0,那么最好采用基数 10,这样才不会意外地得到八进制的值 console.log(parseInt("010")); //返回 8 console.log(parseInt("010", 8)); //返回 8 console.log(parseInt("010", 10)); //返回 10
Output result:
Method 2: Use parseFloat() to convert to floating point number
console.log(parseFloat("12345red")); //返回 12345 console.log(parseFloat("0xA")); //返回 NaN console.log(parseFloat("11.2")); //返回 11.2 console.log(parseFloat("11.22.33")); //返回 11.22 console.log(parseFloat("0102")); //返回 102 console.log(parseFloat("red")); //返回 NaN
Output result:
Method 3 : Use the multiplication operator
If a variable is multiplied by 1, the variable will be automatically converted to a numeric value by JavaScript. After multiplying by 1, the result is unchanged, but the type of the value is converted to a numeric value. If the value cannot be reduced to a legal number, NaN is returned.
var a = 1; //数值 var b = "1"; //数字字符串 console.log(a + (b * 1)); //返回数值 2
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to convert string to number in es6. For more information, please follow other related articles on the PHP Chinese website!