Getting a color in a 0-1 float value

Is there a method gives you the color’s component’s value in a float value in the range 0-1? It’s odd I haven’t found one since you can declare a color in this way (using the 0-1 float value that is).

In case there isn’t one, I quickly wrote this code:

double r = (double)(new Color(0.1F, 0.2F, 0.3F, 0.4F)).getRed();
r /= 256;
System.out.println(r);

This outputs 0.1015625 as the amount of red in the color but you can clearly tell it really is 0.1. Is there a more accurate way of doing this?

If the Color class saves the values as bytes, then there will only be 256 possible values in each channel, which leads to the inaccuracy you’re seeing.

Last but not least, you should divide by 255, not 256.

Generally you shouldn’t rely on float precision. See here for a brief introduction:

With some confusion (I’m new!), thank you for your answer! So basically, there is no way to 100% accurately retrieve the number?

There is no constructor for double’s in color unfortunately. Would you suggest using int’s for putting RGB values in instead?

Which Color class are you using? java.awt.Color ?

That would be correct

Yes, just specify the R, G, B, A integers in the range 0 - 255 if you need an exact color.

No matter the constructor, the java.awt.Color class stores each color channel (RGBA) in 8 bits, so that’s 256 values. Given that floats have over 4 billion values - although a few less in the range 0…1 - you’re bound to lose precision.


		float input = 0.1f;
		int channel = (int) (input * 255.0f + 0.5f);
		float output = channel / 255.0f;

		System.out.println(output);

0.101960786

Thanks to both of you, I’m switching to using the 0-255 way of doing it!