Methods to convert characters into numbers in JavaScript: 1. Use the "parseInt(value)" statement; 2. Use the "parseFloat(value)" statement; 3. Use the multiplication operator, the syntax "value * 1"; 4. Use the "Number(value)" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Use parseInt()
parseInt() is a global method that can convert values into integers. The conversion process is as follows:
First parse the character at position 0. If it is not a valid number, NaN will be returned directly.
If the character at position 0 is a number or can be converted to a valid number, continue to parse the character at position 1. If it is not a valid number, return the valid character at position 0 directly. number.
And so on, analyzing each character one by one from left to right until a non-numeric character is found.
parseInt() will convert all previously analyzed legal numeric characters into numerical values and return them.
console.log(parseInt("123abc")); //返回数字123 console.log(parseInt("1.73")); //返回数字1 console.log(parseInt(".123")); //返回值NaN
Dots in floating-point numbers are illegal characters for parseInt(), so the decimal part of the value will not be converted.
2. Use the parseFloat() function
parseFloat() is also a global method. It can convert the value into a floating point number, that is, it can identify the first occurrence. decimal point, and the second decimal point is considered illegal. The parsing process is the same as the parseInt() method.
console.log(parseFloat("1.234.5")); //返回数值 1.234
The parameter of parseFloat() must be a string in decimal form, and octal or hexadecimal numeric strings cannot be used. At the same time, 0 (octal number identification) in front of the number will be ignored, and 0 will be returned for hexadecimal numbers.
console.log(parseFloat("123")); //返回数值 123 console.log(parseFloat("123abc")); //返回数值 123 console.log(parseFloat("010")); //返回数值 10 console.log(parseFloat("0x10")); //返回数值 0 console.log(parseFloat("x10")); //返回数值 NaN
3. Use the multiplication operator
If the variable is multiplied by 1, the variable will be automatically converted into a numerical 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
4. Use the Number() function
Number() coercion is handled differently from parseInt() and parseFloat() methods. Number() conversion It's the whole, not the local value.
console.log(Number("123abc")); //返回NaN console.log(Number("123")); //返回数值123
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to convert characters into numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!