How to round down a double to the nearest smaller int in C?
Question
I've got a double:
double d = 25.342;
How can I convert it to 25
value?
If it were -12.46
I'd like to get -13
.
Solution
int i = (int)floor(25.342);
OTHER TIPS
int i = (int)floor(25.342);
Note this will convert 12.99999 to 12.
Ref:
Where x is your 25.342
int i = x >= 0 ? (int)(x+0.5) : (int)(x-0.5)
#include <math.h>
#include <stdio.h>
int main(){
double d = 25.342;
double e = -12.99;
printf("%d\n",(int)round(d)); // 25
printf("%d\n",(int)round(e)); // -13
return 0;
}
You may also want to take a look at stdint.h
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow