Why is my OR not working with floats

I have a very basic sketch here but it's not working and I don't understand why. What I want to happen is to set the variable "ambient_temp_group" to "1" if the temperature is 10.0 or 11.0 and to "99" if it's anything else. What happens instead is that it works for when my temperature is 10.0 but not 11.0.

float temperature = 10.0;
int ambient_temp_group;

void setup() {
  Serial.begin(9600);
  delay(1000);

void loop() {

if (temperature == 10.00 || temperature == 11.00)  
     {ambient_temp_group = 1;}

else  ambient_temp_group = 99;
    

Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" Temp Group: ");
Serial.println(ambient_temp_group);

temperature = temperature + 0.1;

if (temperature > 14) {temperature = 10;}

delay(200);

}

Don't attempt to test equality on float variables. Instead, test for the value to be within some small range around the point of interest.

1 Like

float rarely can be exactly equal to something as they don't have infinite precision

give yourself a small interval around 10 or 11

EDIT: @gfvalvo was faster :slight_smile:

1 Like

Thank you, I will try that!

You have that if() to set group to 1 when track a temperature equals exactly 10.0 or 11.0, not the values in between that range. Try changing it to:

// If greater or equal to 10.00 and less or equal to 11.00)
if (temperature >= 10.00 && temperature <= 11.00)  
  ambient_temp_group = 1;
else  
  ambient_temp_group = 99;

EDIT: you both were too fast! :slight_smile:

If you just want to be near 10.0, rather than between 10.000 and 11.000 you can use

    if (abs(temperature - 10.0) < 0.1) {… 

the absolute difference between the target and the measurement.

HTH

a7

Something to be aware of, printing to two decimal places may show 11.00, but the actual float can be anywhere from 10.995 to 11.004999….. , and since the float is in binary form, there may not be an exact representation of a decimal number.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.