0

I am trying the solutions in this thread: RGB to Hex and Hex to RGB without luck:

function rgbToHex(my_color) {
             r = my_color.r;
             g = my_color.g;
             b = my_color.b;
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

When I call the above with the following:

my_color= {r: 51, g: 51, b: 9.180000000000003} 

I get:

#333309.2e147ae 

which doesn't seem right. Considering how my input is formatted, am I supposed to pass values in a different way?

Community
  • 1
  • 1
Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564
  • Have you read [***this***](http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx/)? – SpYk3HH May 08 '14 at 13:59
  • The problem is in that you're coding floating values to ARGB format, every channel (`r`, `g` and `b`) should be an integer in the range [0, 255] for this to work – higuaro May 08 '14 at 14:01
  • 1
    What are you expecting to get? If you only need the first 6 hex digits, you should remove the fractional part of each of the parameters before you shift bits and convert into hex – devnull69 May 08 '14 at 14:02

2 Answers2

1

You may trim out float point values for the function to work properly.. You could use this:

function rgbToHex(my_color) {
             r = Math.floor(my_color.r);
             g = Math.floor(my_color.g);
             b = Math.floor(my_color.b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
edrian
  • 4,501
  • 5
  • 31
  • 35
1

Your function only works for integer values now, so that if there are float numbers in the color object the return is not doing its job properly.

I personal recommend using the built in function for javascript to return integer values from any given value.

The function is parseInt()


In your case the code would change from

function rgbToHex(my_color) {
         r = my_color.r;
         g = my_color.g;
         b = my_color.b;
         return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

to

function rgbToHex(my_color) {
         r = parseInt(my_color.r);
         g = parseInt(my_color.g);
         b = parseInt(my_color.b);
         return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
Friedrich
  • 2,211
  • 20
  • 42