parseInt() to convert an integer that's expressed as a string into an actual number type that one can use in calculations.
The MDN defines the use of
parseInt() as follows:
parseInt(string) parseInt(string, radix)
string is the value to parse. In the case that it's not a
string type, it is internally converted to a
string before the parsing occurs.
radix is a value between 2 and 36 which is the base of the
string parameter value. It does NOT default to base 10 if this parameter is omitted. For example, a string with the prefix "0x" will default to base 16, hexadecimal. To learn in greater detail how various inputs are treated, please refer to the MDN article on parseInt() for more details.
parseInt() can be used to convert numbers to and from various bases if one understands how the radix parameter functions.
parseInt("23", 4) parseInt("0x23") parseInt("23", 2)
11 35 NaN
In each case we are answering the question: "What is the base 10 value of 23 in base 4? in base 16? in base 2?"
- "23" in base 4 is
2 * 4 + 3, or
11in base 10.
- "0x23" implies base 16.
2 * 16 + 3, or
35in base 10
- "23" in base 2 is
NaN, since base 2 digits can only include
Imagine how useful this could be if someone needs you to quickly interpret binary "1110010"!
will give us the correct base 10 number:
toString(radix) with a number object overrides the the Object object method
toString(). When used with number objects,
toString(radix) returns a string representation of the number object in the specified base.
toString(radix) answers the question: "How do I write the value 23 in base 4? in base 16? in base 2?"
let num = 23 num.toString(4) num.toString(16) num.toString(2)
And the output:
113 17 10111
toString() act as inverses of each other:
let num = 23 parseInt(num.toString(4), 4) parseInt(num.toString(16), 16) parseInt(num.toString(2), 2)
And the result:
23 23 23
toString(2) is particularly useful if you need to generate the binary representation of a number for any reason. Or how about converting a hexadecimal number (base 16) into its binary equivalent?
"111110100" (in case you were wondering, this is 500 in base 10!)
I hope this brief exploration of these two related methods leaves you with a greater understanding of how they go beyond converting integers to strings and vice versa. They can be used to translate numbers to and from other bases, as well!
Top comments (0)