evaluating doubles in an if statement

I have the following code on my Arduino Mega2560

double t = .1;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  
}

void loop() {
  // put your main code here, to run repeatedly: 
  Serial.println(t);
  if(t == 0.70){
    Serial.println("hi there");
  }
  delay(100);
  t = t + .1;
}

unfortunately "hi there" is never printed. Any help on how to compare doubles? Do I need to multiply and cast to an int?

Thanks!!!

EDIT:: Can someone move this to the programming questions section. Sorry!

A float may not give an exact representation of any given number, so testing for equality is never a good idea.
Try ">=" or "<="

Note also that to the Arduino, double and float datatypes are exactly equivalent, only 32 bit floating point values are supported.

Because of the binary representation of a floating-point, there are rounding errors and all 32-bits are rarely exactly-equal. That is, == is tricky with floating point numbers.

Greater-than & less-than are better choices. If you look for a number >69.5 and < 70.5, (or something like that) it should work.

This might work too:
if(t == (double)0.70){

That will force 0.70 to be represented as a double, and since t and 0.070 share the same format, they should both share the same binary format. But, I'd just try to avoid == with floating point.

That worked, Thanks!!
I just re-wrote the statement to

t > 0.60 && t < 0.80

(interesting problem though, this must have something to do with the way Arduino handles doubles, yes?)

and since t and 0.070 share the same format, they should both share the same binary format

But "t" was produced by summing possibly inexact fractions, so there's no guarantee that they'd add up to any representation of 0.7.

Arduino doesn't handle doubles, only floats.
This problem isn't limited to the Arduino.

No. It has to do with the way "floating point" works.

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

One can use == to compare floats but as the floats mostly are the result of math with rounding errors one must take these rounding errors into account.

This can be done by comparing the absolute difference with a small number

if ( abs(f1-f2) <= someVerySmallNumber) ...

or better encapsulate this in a function

bool feq(float f, float g, float precision)
{
  return (abs(f-g)  < precision);
}

IMHO," t > 0.60 && t < 0.80" might not work as planned. if it were by chance exactly on in it increases by .1, you could trigger 3 times. try a smaller range.

why not just use integers?:

int t = 1;
if(t == 7){
    Serial.println("hi there");
  }
  delay(100);
  t = t + 1;

but, you ma be after a situation that you have to use doubles, so this may not be a good answer :frowning: