abs function not giving exact required value

I have been trying this code to match a float value with another float value using the abs function.Here is the code:

float li=0;
float d=2;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
li=li+0.1125;
Serial.println(li);
if(abs(li-d)<0.2)
{
  Serial.println('h');
  exit(0);
  }
 
}

I want the li value to reach nearest to the d value.The difference between the values should be less than 0.2.If true,then the if statement should execute.But, this is the output which I am getting:

0.11
0.22
0.34
0.45
0.56
0.68
0.79

The if statement exits after 0.79.Help!!! I am new to Arduino.

Hi there!

I looked over your code and for the life of me could not find anything wrong, so I took the code and ran it on my board. Below is a screenshot of the serial window. Is this what you are trying to get?

Maybe try fabs() instead of abs. The 'f' implies it is better suited to floating point arithmetic. The arduino 'abs()' function is anyway a preprocessor marcro defined in Arduino.h

The other thing to do is to simply test the result of your calculation and, if negative, multiply by -1 or subtract if from zero instead of using abs() etc.

aditya_orangi:   exit(0);

"There's your problem."

exit() disables interrups**, which stops outgoing Serial traffic and leaves a lot of your output hanging in the buffer. Add Serial.flush() before the exit().

** on AVR; on Due it may be different which would explain the different result in #1.