# if statement does not work with fraction, but works with decimal equivalent

I'm trying to trouble shoot a problem with my code and narrowed it down to my if statement not working with a fraction.

The below code does not work and returns 0

``````for(float i=0; i <= 1; i += .0001){
t += .0001;
if(t >= 1/440){ //Fraction
t = 0;
}
Serial.println(t*100);
delay(100);
}
``````

But when I replace the 1/440 with its decimal equivalent (.0022727) it works fine and counts from 0 to 2.2

``````for(float i=0; i <= 1; i += .0001){
t += .0001;
if(t >= 0.0022727){ //Decimal
t = 0;
}
Serial.println(t*100);
delay(100);
}
``````

If there is a simple way to use a fractional value instead of a decimal value it would make my application much similar. Thanks.

• Always present float calculations like this 1.0/440.0 and not 1/440 to prevent these being treated as integer calculations. Avoid using floats in comparisons especially '==' comparisons. Apr 26 at 4:27
• @6v6gt Please read When shouldn't I comment?. If you aren't requesting clarification from the author (or the other couple of reasons to comment on the question) then you should be posting an answer instead. Apr 26 at 5:40
• @6v6gt You may want to look at this. I don't know if it will matter being as old as it is, but you could weigh in on it if you have the interest; I don't. But I would them to make up their minds about it. Apr 26 at 15:18
• @NickGammon One problem with giving a formal answer in such a borderline off topic case (this one could fail if the often applied test "non-Arduino specific" is applied and it does anyway have a general C/C++ look to it) is that the answerer risks losing a couple of Brownie points if someone decides to assert that it is off topic and starts down-voting both the question and the answer. Some answers which I have put considerable effort into, and the OP could not have known that the solution to the problem was "Non-Arduino specific", have ended up with a -1 score. Apr 27 at 18:22
• @6v6gt Yeah, I agree. I try to ignore the occasional down-vote as there are people who like to nitpick that sort of stuff. It's true it's really a programming question, but we do have a `programming` tag after all, so I think programming questions are OK. Especially if beginners to Arduino maybe think that the Arduino has different rules to C++. Apr 27 at 21:51

`1/440` will be treated as an integer expression, returning zero.

To make it work, make one or both operands a floating-point type. In your case:

`````` if(t >= (float)1 / 440){ //Fraction
t = 0;
}
``````

Or:

`````` if(t >= 1.0/440){ //Fraction
t = 0;
}
``````