You can use the toString() method to convert a decimal number to hexadecimal. This is the main purpose of this method. But it is officially supported, meaning you don’t need to carry out a manual conversion.
The syntax is quite straightforward:
For instance, this is how the toString() method is invoked most of the time:
const num = 128; console.log(num.toString());
The example above just gives us the string with the exact representation of the original number. Luckily, if you invoke the toString() method on objects inheriting from the Object type, such as Number, you can use optional parameters to change the base of the numeral system.
In particular, if you already have a Number object, you can use the radix parameter to specify the base used for the string representation.
Since we want the hexadecimal representation, the radix parameter should be 16.
var num = 128; console.log(num.toString(16)) num = 16559; console.log(num.toString(16))
This conversion applies to negative decimal values as well:
const num = -16559; console.log(num.toString(16))
If you prefer to have the letter from a to f in the hex representation in upper case, you can use the toUpperCase() method to convert it:
const num = 16559; console.log(num.toString(16).toUpperCase())
Additionally, this conversion is applicable to not just integers but also floating-point numbers.
const num = 10.5; console.log(num.toString(16).toUpperCase())
The issue gets a little more complicated if your original number doesn’t have a base of 10. In this case, you will need to use the toString() method in conjunction with the parseInt() function to make the conversion to hexadecimal.
For instance, you can use the following code to convert 1372 in octal to hexadecimal:
const oct = “1372”; const dec = parseInt(oct, 8); console.log(dec); const hex = dec.toString(16); console.log(hex);
The above statement will take the string parameter and return an integer using the base you have specified with the rapid parameter (between 2 and 36). In the above example, the 1372 number in octal has been converted to 762 in decimal before going through another conversion to hexadecimal (2fa).
toString() method of Number objects with the radix parameter. The conversion is simple with decimal values. If you have binary or octal numbers, for instance, you will need to use the
parseInt() function to convert them to decimal first.
If you want to check whether your string represents a valid number before making the conversion, you can follow the suggestions in this guide.