javascript tutorial - [Solved-5 Solutions] Decimal to hex - javascript - java script - javascript array



Problem:

How to convert decimal to hex in JavaScript?

Solution 1:

Convert a number to a hexadecimal string with:

hexString = yourNumber.toString(16);
click below button to copy the code. By JavaScript tutorial team

and reverse the process with:

yourNumber = parseInt(hexString, 16);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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

    return number.toString(16).toUpperCase();
}

click below button to copy the code. By JavaScript tutorial team

Solution 3:

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;
}

click below button to copy the code. By JavaScript tutorial team

Solution 4:

function rgb2hex(r,g,b) {
    if (g !== undefined) 
        return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
    else 
        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

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
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Decimal to hex