Method to convert string to number: 1. Use Number() function, syntax "Number(string)"; 2. Use parseInt() function, syntax "parseInt(string)"; 3 , use parseFloat() function, syntax "parseFloat(string)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Convert string to number
1. Number() conversion function
## The #Number() function converts the value of an object into a number. Pass in a string through the Number() conversion function, which will try to convert it into an integer or floating-point direct quantity. This method can only be converted based on decimal, and non-digits cannot appear in the string. characters, otherwise NaN will be returned.<script type="text/javascript"> var test1= new Boolean(true); var test2= new Boolean(false); var test3= new Date(); var test4= new String("999"); var test5= new String("999 888"); document.write(Number(test1)+ "<br />"); document.write(Number(test2)+ "<br />"); document.write(Number(test3)+ "<br />"); document.write(Number(test4)+ "<br />"); document.write(Number(test5)+ "<br />"); </script>
1 0 1256657776588 999 NaN
2. parseInt() function
It is a global function and does not belong to any class method. And only parses integers. If the string prefix is "0x" or "0X", parseInt() interprets it as a hexadecimal number. It skips any number of leading spaces, parses as many numeric characters as possible, ignores what follows, and returns NaN if the first non-space character is a non-numeric character. For example: parseInt() can also receive a second optional parameter. This parameter specifies the base of number conversion. The legal value range is 2~36, for example:3. parseFloat() function:
It is also a global function and does not belong to any class method. It can be parsed Integers and floating point numbers. It does not recognize the hexadecimal prefix "0x" or "0X". It also skips any number of leading spaces when parsing, parses as many numeric characters as possible, ignores what follows, and returns NaN if the first non-space character is a non-numeric character. For example: [Related recommendations:The above is the detailed content of How to convert string to number in javascript. For more information, please follow other related articles on the PHP Chinese website!