float bug?

hello,


void foo(int dir)
{
if (dir == 0)
{
gFloat -= 0.1f;
if (gFloat <= 0.f)
gFloat = 0.f;
}
else
{
gFloat += 0.1f;
if (gFloat >= 1.f)
gFloat = 1.f;
}

std::stringstream ss;
ss << (int)(gFloat*100.0f) << "%";
}

when i reach 100% and then i go back i dont get 90,80,70 etc.. but i get 89,79,69 etc... until i reach 0... why this?
Floating point numbers can't store all numbers exactly and operations on them can have rounding errors. When you cast the float to int it just cut off the decimal part. When you think you have 90 you probably have a number that is slightly less than 90 so when the decimal part is thrown away you get 89. If you actually want to round the number you could use std::round. You could also use std::setprecision to change how many decimal digits to show.
Floating point numbers are inherently problematic. For example, 0.1 is impossible to be represented in binary with 100% accuracy.
Think about it, how would you go about storing anything that doesn't have a denominator representable as a power of 2? You'll always be left with an infinite decimal representation, which must be truncated due to finite storage space, for numbers that do not fulfill x*(1/2^n).
Topic archived. No new replies allowed.