views:

18594

answers:

7

How do you convert decimal values to their hex equivalent in JavaScript?

+53  A: 
yourNum = yourNum.toString(16);

and reverse the process with:

yourNum = parseInt(yourNum, 16);
Prestaul
+3  A: 

The code below will convert the decimal value d to hex. It also allows you to add padding to the hex result. so 0 will become 00 by default.

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}
Luke Smith
This won't properly handle negative values. decimalToHex(-6, 4) would return 00-6.
JonMR
A: 
var number = 3200;
var hexString = number.toString(16);

The 16 is the radix and there are 16 values in a hexidecimal number :-)

Danny Wilson
+5  A: 

If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The javascript function toString(16) will return a negative hex number which is usually not what you want. This function does some crazy addition to make it a positive number.

function decimalToHexString(number)
{
    if (number < 0)
    {
     number = 0xFFFFFFFF + number + 1;
    }

    return number.toString(16).toUpperCase();
}
Tod
+3  A: 
function dec2hex(i)
{
  var result = "0000";
  if      (i >= 0    && i <= 15)    { result = "000" + i.toString(16); }
  else if (i >= 16   && i <= 255)   { result = "00"  + i.toString(16); }
  else if (i >= 256  && i <= 4095)  { result = "0"   + i.toString(16); }
  else if (i >= 4096 && i <= 65535) { result =         i.toString(16); }
  return result
}
+1  A: 

AFAIK comment 57807 is wrong and should be something like: var hex = Number(d).toString(16); instead of var hex = parseInt(d, 16);

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}
I've updated my reply with this fix :)
Luke Smith
A: 

Without the loop :

function decimalToHex(d) {
  var hex = Number(d).toString(16);
  hex = "000000".substr(0, 6 - hex.length) + hex; 
  return hex;
}

//or "#000000".substr(0, 7 - hex.length) + hex;
//or whatever
//*Thanks to MSDN

Also isn't it better not to use loop tests that have to be evaluated eg instead of:

for (var i = 0; i < hex.length; i++){}

have

for (var i = 0, var j = hex.length; i < j; i++){}
mystifeid