C weird behavior when dividing two floats

Viewed 176

I have some code that I run on an ESP32 written in Arduino. The problem is that my result is rounded up when it should not be.

float step_value = (float)abs(levels_values[i] - levels_values[i - 1]) / abs(levels_percentages[i] - levels_percentages[i - 1]);
float percentage_diff = (float)abs(current_value - levels_values[i - 1]) / step_value;

Serial.println(step_value);   
Serial.println(2.00/step_value);
Serial.println(2.00/0.07);

And inside the console the output is:

0.07
30.00
28.57

Why is that if I divide by the variable, I get a rounded value and when I divide by the value of the variable I get the right value.

levels_values and levels_percentages vectors are of type int

1 Answers

The value of step_value is about .0666667. Serial.println(step_value) is not printing the complete value; it is rounding it to two decimal digits after the decimal point.

Serial.println(2.00/step_value) prints “30.00” because 2.00/.0666667 is about 30.

Serial.println(2.00/0.07) prints “28.57” because 2.00/.07 is about 28.57.

Related