Stop Being Carbon

Icon

JavaScript: Number to Hex

I suppose that Justin wanted to play around with the shifting operators, because there’s an easier way to convert a number from decimal to hex representation:

Number.prototype.toHex = function() {
    return this.toString(16)
}
 
(255).toHex(); //ff
[255, 255, 255].invoke('toHex').join(''); //ffffff

Category: Technology

Tagged:

2 Responses

  1. It was an experiment with shift operators, but I wasn’t aware of the toString method, so I learned something new. Is that cross-browser? If so, what’s the business with toColorPart using toPaddedString?

  2. Christoph says:

    Should work for JavaScript implementations > 1.0 (so basically all). I think toPaddedString basically insures that the hex number is two digits long.

Leave a Reply