convert a number from base 10 to base 16 in javascript

To convert a number from base 10 to base 16 in javascript, we can use the toString() method with a base argument of 16. Here's an example code snippet:

index.tsx
const num = 255;
const hexNum = num.toString(16);

console.log(hexNum); // output: "ff"
88 chars
5 lines

In this example, we first declare a variable num with the decimal value 255. Then, we call the toString() method on num with an argument of 16 to convert it to a hexadecimal string. The resulting hexNum variable holds the string "ff", which is the hexadecimal representation of 255.

Note that the resulting string will always be in lowercase by default. If you need to convert it to uppercase, you can simply use the toUpperCase() method:

index.tsx
const num = 255;
const hexNum = num.toString(16).toUpperCase();

console.log(hexNum); // output: "FF"
102 chars
5 lines

gistlibby LogSnag