Dec2Hex

Converts a decimal value into a hex value. This helps converting RGB colors to HEX.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
*/
X

Url: http://www.jonasjohn.de/snippets/javascript/dec2hex.htm

Language: JavaScript | User: ShareMySnippets | Created: Oct 16, 2013