RGB to hex and hex to RGB RGB to hex and hex to RGB javascript javascript

RGB to hex and hex to RGB


Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {  var hex = c.toString(16);  return hex.length == 1 ? "0" + hex : hex;}function rgbToHex(r, g, b) {  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);}alert(rgbToHex(0, 51, 255)); // #0033ff