Home >Web Front-end >JS Tutorial >javascript how to convert string to number

javascript how to convert string to number

青灯夜游
青灯夜游Original
2021-04-27 16:42:253154browse

Conversion method: 1. Use parseInt() function, syntax "parseInt("string")"; 2. Use parseFloat() function, syntax "parseFloat("string")"; 3. Use Number() function, syntax "Number("string")".

javascript how to convert string to number

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn