Q: ... function that transforms 3.55 to 3.6, 0.0499999 to 0.0 ...?
A: Using @Kninnug answer, but to 1 decimal place.
f = round(f * 10) / 10.0;
It will give you 3.5
because the number f
is not originally 3.55. True, you initialized f
using the text "3.55", but C
and your computer were unable to exactly represent that number. There is no (float) 3.55 on your system. Instead f
has a value about 3.549999952...
as it is the closest choice.
Should you still want to show f
rounded to 3.6 rather than 3.5, you need to nudge f
up a bit. Nudging when it is 3.549999952...
so it has a value >= 3.55 and when f
is 0.04999990016...
(0.0499999 is not exactly representable either) that the same nudging keeps it f
< 0.5.
The smallest we can increase f
and see a change is nextafterf(f, g)
. g
is the value you wish to move toward.
3.549999952... --> 3.550000190...
0.04999990016... --> 0.04999990389...
printf("%.1f\n", nextafterf(f, 2*f));
// prints 3.6 when f is 3.549999952...
// prints 0.0 when f is 0.04999990389...
Recommend you review the reference in @Oli Charlesworth answer.