May 5, 2007
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
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?
Should work for JavaScript implementations > 1.0 (so basically all). I think toPaddedString basically insures that the hex number is two digits long.