tags:

views:

124

answers:

1

I'm probably doing this the hard way, so what's the cleanest way to convert from a percentage to a string containing one part of an RGB hex value?

This is what I've got:

//dealing with small percentages, need to magnify the color differences.
double increaseVisibilityFactor = 5;     

double percent = someDouble / someOtherDouble;
double redLightenAmount = 1 - (percent * increaseVisibilityFactor);
if (percent > 0 && redLightenAmount < 0) { redLightenAmount = 0; } //overflow

int increaseWhiteBy = (int)(redLightenAmount * 0xFF);

string hexColor = increaseWhiteBy.ToString("X");
if (hexColor.Length < 2) { hexColor = "0" + hexColor; }
hexColor = "FF" + hexColor + hexColor;

Some of the above lines could obviously be combined (i.e. conversion to int and then string) but I'm wondering if there are overall flaws or a better way of doing this?

+1  A: 

Yes, that can be done easier:

  string hexcolor = string.Format("FF{0:X2}{0:X2}", increaseWhiteBy);
Hans Passant
Do you know of any better way to do the `double` to "`int` percentage of 255" conversion?
jball
I see nothing wrong with what you do now.
Hans Passant