Is there a function to round a float in C or do I need to write my own?
float conver= 45.592346543;
Would like to round actual value to one decimal place. conver = 45.6
Thanks.
Is there a function to round a float in C or do I need to write my own?
float conver= 45.592346543;
Would like to round actual value to one decimal place. conver = 45.6
Thanks.
#include "math.h" // can't input less than and greater than :)
double round(double x);
float roundf(float x);
Don't forget to link with -lm. See also ceil(), floor() and trunc().
Sure, you can use roundf(). If you want to round to one decimal, then you could do something like: roundf(10 * x) / 10
Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf()
.
I think there is another way to do it, though. You can try ceil()
and floor()
to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil()
and floor()
only work on double
s though.
EDIT: Also, for floats, you can use truncf()
to truncate floats. The same +0.5 trick should work to do accurate rounding.
As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;
//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;
printf("conver is now %f\n",conver);
return 0;
}
I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.