Convert decimal to hexadecimal in javascript & reactjs – Code Example

Total
0
Shares

To convert a decimal number to hexadecimal in javascript and reactjs, use these steps –

  1. Run a loop till provided value become 0
  2. Take mod by 16 and convert the number into hexcode (0-F).
  3. Set the value as value divided by 16

Code Example –

function decimalToHex(x) {
  var parsed = parseInt(x, 10);
  if (isNaN(parsed)) { return 0; }
  
  hexstr = ""
  while(parsed > 0) {
    var value = parsed % 16
    hexstr = (
      value == 10 ? "A" : (
        value == 11 ? "B" : (
        value == 12 ? "C" : (
        value == 13 ? "D" : (
        value == 14 ? "E" : (
        value == 15 ? "F": value)))))) + hexstr
    parsed = parseInt(parsed / 16)
  }
  
  return '0x'+ hexstr;
}

console.log(decimalToHex(' 245'));
// expected output: "0xF5"

Source: MSDN