Tip: Convert decimal number to hexadecimal

Angelos Chalaris · JavaScript, Math · Sep 21, 2022

Numeric values are represented in decimal format by default, when converted to strings. If you want to display them in hexadecimal format, you can use Number.prototype.toString() and pass the base you want to use (16) as an argument.

const decimalToHex = dec => dec.toString(16);

decimalToHex(0); // '0'
decimalToHex(255); // 'ff'

Conversely, the opposite might also be needed. You can use parseInt() to convert a string to a number in a given base. If you don't specify a base, it will default to 10.

const hexToDecimal = hex => parseInt(hex, 16);

hexToDecimal('0'); // 0
hexToDecimal('ff'); // 255

Recommended snippets & collections

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Number to decimal mark

    JavaScript, Math

    Converts a number to a decimal mark formatted string.

  • When working with numeric arrays in JavaScript, you might find yourself in need of finding the minimum or maximum value. Here's a quick and easy way to do it.

  • Digitize number

    JavaScript, Math

    Converts a number to an array of digits, removing its sign if necessary.