Do it like this:
int round_zero_digits(float x)
{
return x + 0.5;
}
Or more general:
#include <math.h> /* for pow() */
...
float round_n_digits(float x, unsigned int n)
{
x *= pow(10., n);
x = (int) (x + 0.5);
while (n--)
{
x /=10.;
}
return x;
}
With round_n_digits(x, 0)
being equivalent to round_zero_digits(x)
.
Update (not using the math
lib):
float round_n_digits(float x, unsigned int n)
{
unsigned int n_save = n;
while (n--)
{
x *= 10.;
}
x = (int) (x + 0.5);
while (n_save--)
{
x /= 10.;
}
return x;
}
Update^2 (the pure C'ish way):
#define ROUND_ZERO_DIGITS(x) ((int) ((x) + 0.5))
float round_n_digits(float x, unsigned int n)
{
unsigned int n_save = n;
while (n--)
{
x *= 10.;
}
x = ROUND_ZERO_DIGITS(x);
while (n_save--)
{
x /= 10.;
}
return x;
}
With ROUND_ZERO_DIGITS()
being the macro'ed version of the function round_zero_digits()
.