Conversion method: 1. Use parseInt() function, syntax "parseInt("string")"; 2. Use parseFloat() function, syntax "parseFloat("string")"; 3. Use Number() function, syntax "Number("string")".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Convert string to number
①parseInt() function: It is a global function, does not belong to any class method, and only parses integer. 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:
The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal or any other base string into an integer. The base is specified by the second parameter of the parseInt() method. The legal value range is 2~36, for example:
②parseFloat() function: It is also A global function, a method that does not belong to any class, it can parse 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:
③ Pass in a string through the Number() conversion function, and it will try to convert it into an integer or floating point number direct quantity. This method can only be based on Convert to decimal, and non-numeric characters cannot appear in the string, otherwise NaN will be returned.
Number(false) 0 Number(true) 1 Number(undefined) NaN Number(null) 0 Number( "5.5 ") 5.5 Number( "56 ") 56 Number( "5.6.7 ") NaN Number(new Object()) NaN Number(100) 100
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of javascript how to convert string to number. For more information, please follow other related articles on the PHP Chinese website!