Other than using any inbuilt function like ceil
and floor
how can you round a floating point number?
I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2
I wrote some logic but stuck in the middle
float a = 2.24;
int b = a*100;
int result n, i =0;
while(i>2)
{
n = b%10;
i++;
}
if(n >5)
{
c = b%10;
c = c/10 + 1;
}
I tried lot of inbuild function but all that not workign for my diab compiler
// totalDist = roundf(totalDist * 10) / 10.0;
// totalDist = floor(totalDist * pow(10., 1) + .5) / pow(10., 1);
totalDist = floorf(totalDist * 10 + 0.5) / 10;
planning to write my own logic
float a = 2.24;
float b = roundf(a*10.0f)/10.0f;//roundf in C99
If you just want to round the number for output purposes, then the %.1f
format string is indeed the correct answer.
printf("%.1f", 2.14);
or If you actually want to round off value then something like this work
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = floorf(val * 100 + 0.5) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Usually we use nearest
method
BLUEPIXY's answer is good. But in general; floating point multiplication is faster than division, so if speed is relevant; multiply by 0.1 instead of dividing by 10.
Because my old answer needs lot of careful programming to make it work
You can easily check if a (positive/negative) number will be rounded up or down by (adding/subtracting) 0.5. Then you can truncate the result and take your answer. Also, in order to support deeper level of round as you want you can let the user specify how many decimal places of round the want, and voila:
long double round_f(long double number, int decimal_places)
{
assert(decimal_places > 0);
double power = pow(10, decimal_places-1);
number *= power;
return (number >= 0) ? ((long long)(number + 0.5))/power : ((long long)(number - 0.5))/power;
}
And here you can see a working example.
You can use sprint:
#include <stdio.h>
int main(void)
{
float a = 2.24;
int size;
char num[8] = {0};
sprintf(num, "%d", (int) (a * 100));
for (size=0; num[size]; size++);
size--;
if (num[size] < '5') {
num[size] = '0';
} else {
num[size] = '0';
if (num[size-1] == '9')
num[size-1] = '0';
else
num[size-1]++;
}
printf("a = %f\n", a);
printf("num = %s\n", num);
return(0);
}
You can see the logic. Finally you can revert the string to integer and multiply by 100.
EDIT: It's only the logic. See comments below for what is needed to fully work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.