Home >Web Front-end >JS Tutorial >How to convert string to number in javascript
Method: 1. Use the Number() function, the syntax format is "Number (string object)"; 2. Use the parseInt() function, the syntax format is "parseInt (string object)"; 3. Use parseFloat () function, syntax format "parseFloat (string object)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Convert javascript string to number
①Use Number() function
Pass Number The () conversion function passes in a string, and it will try to convert it into an integer or floating point number literal. This method can only convert based on decimal, and non-numeric characters cannot appear in the string, otherwise NaN will be returned.
Number("023") // returns 23 Number(023) // returns 19
Note: 023 is actually an octal number, and no matter what you do, it returns 19; the same is true for hexadecimal numbers without single or double quotes.
② Use the parseInt() function
It is a global function, 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:
[Recommended learning: javascript advanced tutorial]
parseInt() can also receive a second optional parameter, This parameter specifies the base for number conversion. The legal value range is 2~36, for example:
③ Use the parseFloat() function:
It is also a global function and does not belong to any class method. 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:
For more programming-related knowledge, please visit: Introduction to Programming! !
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!