Dec2Hex

Converts a decimal value into a hex value. This helps converting RGB colors to HEX.

function dec2hex(n){
    n = parseInt(n); var c = 'ABCDEF';
    var b = n / 16; var r = n % 16; b = b-(r/16); 
    b = ((b>=0) && (b<=9)) ? b : c.charAt(b-10);    
    return ((r>=0) && (r<=9)) ? b+''+r : b+''+c.charAt(r-10);
}
 
/*
    Examples:
    ---------
 
    rgb(255, 0, 0) = red color = FF0000
 
    dec2hex(255) => FF
    dec2hex(0) => 00
    dec2hex(0) => 00
 
    ------------------------------------
 
    rgb(215, 230, 250) = light blue = D7E6FA
 
    dec2hex(255) => D7
    dec2hex(0) => E6
    dec2hex(0) => FA
*/
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Marc November 28, 2009 at 19:26
one small comment ;)

rgb(215, 230, 250) = light blue = D7E6FA

dec2hex(255) => D7
dec2hex(0) => E6
dec2hex(0) => FA

should be:

rgb(215, 230, 250) = light blue = D7E6FA

dec2hex(215) => D7
dec2hex(230) => E6
dec2hex(250) => FA

;)
Trogdor August 21, 2009 at 23:36
There is a built-in javascript method for this:

n.toString(16);
(215).toString(16); // "d7"