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!
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.
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
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