It seems that your input values are not integers (have decimal places = digits after the decimal mark). When casting such floating point values, the decimal places are ignored. To implement rounding to nearest, add 0.5 before casting:
int val = static_cast<int>(someDoubleVal + 0.5);
The next problem is the possible loss of data. The integer part of
double
floating point numbers may be much larger than the number of digits that can be held by an
unsigned char
. This will be complained by the compiler (as error or warning depending on the compiler settings). The simplest approach to avoid the warning is using classic C casting:
unsigned char val = (unsigned char)(someDoubleVal + 0.5);
But this should be only used when you are sure that the input values are always in the range of 0 to 255. With RGB values, you might just limit the values using a function:
unsigned char doubleToUChar(double val)
{
unsigned char uc = 0;
if (val >= 255.)
uc = 255;
else if (val > 0)
uc = (unsigned char)(val + 0.5);
return uc;
}