Understanding of parseInt() funtion in JavaScript
parseInt() function in javascript is used to parse a string element and returns as an integer.
Syntax:
It takes two parameters:
- String: The string to be converted to an integer.
- Radix (optional): An integer between 2 and 36 that represents the base of the numeral system used in the string. This is an optional parameter, and if not specified, JavaScript assumes the following:
- If the string begins with "0x" or "0X", it is parsed as a hexadecimal number. (Example is given at last). It is always better to specify by the programmers for clarity and understanding.
Syntax: parseInt(String,radix) or parseInt(String)
- Otherwise, it is parsed as a decimal number.
Syntax: parseInt(String)
Let us see the examples for a better understanding
Radix:
The result will be
The conversion of hexadecimal to decimal numbers has been shown in the below image
Some examples of String
I initialize two variables as String.
The result of the above code is
Example 1
When I try to add, it concatenates the values
Result
Example 2
When I try to add two numbers by getting the values, the
output would be NaN. Because 'value' is undefined and it is a string.
Result
Example 3
Use parseInt but add the numbers by getting the value of
two numbers. Here also the output would be NaN. Because 'value' is undefined.
Result
Example 4
Converting string to an integer using parseInt() function and
adding the two integers
The result would be the expected one
Let me know your thoughts in the comments!
Comments
Post a Comment