0

0I'm developing some kind of buttons (really they are images) that when they're disabled (not by enabled = false) they have and opacity value of 0.1. So, with a simple checking of opacity in the tapping event I can know if it's enabled or disabled.

But, when I set the disabled value for the opacity (0.1) and I debug and check the execution I have a strange behaviour: opacity values are not exactly 0.1, but slightly bigger. So, when I check if ( btnLocateMeControl.Opacity == 0.1 ) always returns false because it isn't exact.

Here the screenshot when debugging:

enter image description here

Any idea why is happenning? Any elegant solution that it's not to check if opacity is not between 0.09 - 0.11 ?

Thanks!

jazb
  • 5,498
  • 6
  • 37
  • 44
  • 2
    Because you're comparing floating point numbers, which is always fraught with peril: https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp – Rufus L Dec 19 '18 at 07:47
  • Why not just implement an `Enabled` property, where you can change the opacity in the setter? Then you have a nice, reliable `bool` to relay the state. – Rufus L Dec 19 '18 at 07:48
  • 1
    0.1 cannot be represented exactly as floating point number – Klaus Gütter Dec 19 '18 at 07:49
  • @Rufus L never thought of that. I'm going to try with a simple function that checks if the given control has opacity between secure values. Thanks! – Imanol Zubiaurre Dec 19 '18 at 07:55
  • @RufusL You can write an answer so that the question can be closed :-) – Martin Zikmund Dec 19 '18 at 09:02

1 Answers1

0

This is my "solution" for the problem. Not the most elegant, but it works and it's easy to implement.

//if (btnGPSControl.Opacity == 0.1) return; // Old problematic part
if (!IsEnabledControl(btnGPSControl)) return;  // New code

And the function to check opacity values:

    private bool IsEnabledControl(Image btnControl)
    {
        return !(0.099 < btnControl.Opacity && btnControl.Opacity < 0.101);
    }