JavaScript parseInt

 The main function of JavaScript parseInt is to convert a string into a number. Binary, octal, hexadecimal, and thirty-two digits can be used to parse strings. The usage should be simple first, but some carry concepts are needed to make no mistakes. In the JavaScript world, 0x or 0X at the beginning of a string is hexadecimal. For example, 0x3, 0x5, etc. are all hexadecimals. If 0 is not followed by x, it is octal, such as 03, 05, etc. , Are all octets, JavaScript parseInt parses the string according to these carry rules and returns a number.


Basic syntax of JavaScript parseInt function

parseInt( string, radix)


The first parameter string in parseInt is the string to be parsed and is a required item. The second parameter radix is ​​the carry method. If it is not filled in, the default decimal is used as the analysis rule. The number range of the radix parameter is between 2 and 32. If it exceeds this range, the parseInt function can only return NaN. Although radix is ​​an optional item, JavaScript has a variety of carry methods when processing strings. It is possible that the result of JavaScript parseInt parsing may be wrong due to the string structure. Therefore, it is recommended that the second parameter radix should be written.

JavaScript parseInt function example
<script type="text/javascript">
<!--
 document.write(parseInt("10")); // Pure numbers, return 10 directly
 document.write(parseInt("10", 10)); // Parse string with decimal and return 10
 document.write(parseInt("123x", 10)); // Parse string with decimal and return 123
 document.write(parseInt("08")); // not set Carry rules, unable to parse, return 0
 document.write(parseInt("08",16)); // parse the string in hexadecimal and return 8
 document.write(parseInt("0x8")); // parse the string in hexadecimal Parse the string and return 8
-->
</script>

The first example is only to parse a number, without setting the analysis carry condition, and automatically parse with the default decimal, which is the most basic situation. The second example, parseInt, uses the decimal system, and the third example also uses the decimal system, but the difference is that this time the string of Xiexi contains English letters. parseInt is very smart to filter out x and parse the answer to 123. The fourth parseInt("08") is a problem. From the knowledge of JavaScript , 08 will be regarded as an octet first, but the octet only uses the number 0~7, and there is no number 8, so it will not be solved Answer, so we added the hexadecimal rule in the example on the next line, and successfully parsed the result of 8. In the last example, 0x8 string, JavaScript will automatically start with 0x and use hexadecimal to process the string, so the parsing result is also 8.

Post a Comment

0 Comments