Strange count behaviour

Hi everybody,

Can someone explain why the code below stops counting at 251 ? (see serial print on the capture with yellow).

float test = 0;

float fadeValue(float dutyValue, float currentValue, int stepValue){

    float coef = 1000.0;
    float intCurrentValue = currentValue * coef;

    if(dutyValue > currentValue){
        int intNewValue = intCurrentValue + stepValue;
        Serial.print(currentValue, 4);
        Serial.print(" intCurrentValue=");
        Serial.print(" intNewValue=");
        Serial.print(" stepValue=");
        Serial.print(" coef=");
        Serial.print(" Return Value + = ");
        Serial.println(float(intNewValue / coef), 4);
        return float(intNewValue / coef);
    } else if (dutyValue < currentValue){
        int intNewValue = intCurrentValue - stepValue;
        Serial.print("Return Value - = ");
        Serial.println(float(intNewValue / coef));
        return float(intNewValue / coef);
    } else {
        return dutyValue;


void setup() {

void loop() {
  test = fadeValue(5.4, test, 1);

And if I put the value 2 in the third argument, the count goes well...

Very strange behaviour !

Many thanks for your reply.


I think 0.251 * 1000.0 is coming out to 250.9999. Since 'intCurrentValue' is a 'float', that displays as "251.00" (Serial.print() rounds off floats to the specified number of decimal digits.). But when you add 1 you get 251.9999 which gets truncated to 251 when you store it in 'intNewValue'.

The problem would be more obvious if 'intCurrentValue' was an 'int'.

You could round up by changing:
int intNewValue = intCurrentValue + stepValue;
int intNewValue = intCurrentValue + 0.5 + stepValue;

Yep... as @johnwasser said... float arithmetic is not exact and should be used with caution.

Quote "Floating point numbers are not exact, and may yield strange results when compared. For example 6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference between the numbers is less than some small number"

From here... float - Arduino Reference

Many thanks for your replies and explanations.

It worked with the +0.5.

Thanks again.