Last updated: Mar 4, 2024
Reading timeยท2 min
Number.toString()
on a number literalTo convert a number to hexadecimal, call the toString()
method on the
number, passing it 16
as the base, e.g. num.toString(16)
.
The toString
method will return the string representation of the number in
hexadecimal form.
const num = 42; // โ Convert to Hex const hex = num.toString(16); console.log(hex); // ๐๏ธ "2a" // โ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // ๐๏ธ "2a" // โ Parse back to number const parsed = parseInt(hex, 16); console.log(parsed); // ๐๏ธ 42
The Number.toString()
method formats the supplied number and returns its
string representation.
The only argument we passed to the Number.toString() method is the radix (the base for the conversion).
The hexadecimal numeral system uses 16 distinct symbols, so that's the base
value we should specify.
The hexadecimal system uses 16 symbols to represent numbers:
"0"
to "9"
to represent values 0
to 9
"a"
to "f"
(A
to F
) to represent values 10
to 15
. Note that the
letters are case-insensitive, so 12AB
and 12ab
are considered the same
value.When a base of greater than 10
is provided to the toString
method, the
letters of the alphabet indicate the numerals greater than 9
.
For hexadecimal numbers (base 16) - the letters from a
to f
are used.
const hex1 = (10).toString(16); console.log(hex1); // ๐๏ธ "a" const hex2 = (15).toString(16); console.log(hex2); // ๐๏ธ "f"
Number.toString()
on a number literalIf you call the Number.toString
method directly on the number literal, you
have to wrap it in parentheses.
// โ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // ๐๏ธ "2a" // โ๏ธ SyntaxError: Invalid or unexpected token const hex3 = 42.toString(16);
If you don't wrap the numeric literal in parentheses, JavaScript treats the period as a decimal point.
console.log(5. === 5); // ๐๏ธ true
If you need to parse the hexadecimal value back to a number, use the
parseInt()
function.
const num = 42; // โ Convert to Hex const hex = num.toString(16); console.log(hex); // ๐๏ธ "2a" // โ Parse back to number const parsed = parseInt(hex, 16); console.log(parsed); // ๐๏ธ 42
The parseInt() function
parses the supplied string argument and returns an integer of the specified
radix
.
The function takes the following 2 arguments:
Name | Description |
---|---|
string | A string starting with an integer |
radix | An integer between 2 and 36 that represents the radix |
The hexadecimal numeral system uses 16 distinct symbols, so that's the radix
value we should specify.
You can learn more about the related topics by checking out the following tutorials: