I imagine this is quite simple, probably no more complicated than a cast. Anyway how do you convert a float to int and have it round up or down.
Printable View
I imagine this is quite simple, probably no more complicated than a cast. Anyway how do you convert a float to int and have it round up or down.
when you convert from float to int only the integer part of the float is put in the int, to round up add 0.5 which if the float is 2.5 or more will result in the float being 3.1, thus storing 3 in the int.Code:int num1;
float num2 = 2.6;
num1 = num2 + 0.5;
or if you just want to print a float to a specific precision you can use
Where the .0 is how many decimal places you want, the rounding up is done for you.Code:printf(" %.0f ", num2);
The reason I wanted to know is because i'm converting jiffies into hours,minutes and seconds. A jiffy is 1/100th of a second or 0.01 seconds. I've written some code below which should hopefully format it correctly. There is a problem with this code, see the comments for details. The test integer can be changed for test purposes.
Code:#include <stdio.h>
/*prototypes*/
char* getTime(int clockticks);
int main(){
char* result;
int test = 256000;
result = getTime(test);
printf("%s\n",result);
return 0;
}
char* getTime(int clockticks){
float jiffies,sec,result;
char* time;
int min,hr,seconds;
jiffies = 0.01f;
result = jiffies * clockticks;
seconds = result;
min = seconds/60;
hr = min/60;
/*This section of code causes some
problems, I don't want it to display
more than 60 in the seconds and minutes
category, but I do want it to be able
display for example, 00:04:23 but
since this is greater than 60 seconds
it will display 00:04:00 instead.*/
if(seconds >= 60)
seconds = 0;
if(min >= 60)
min = 0;
if(hr < 10 && min < 10 && seconds < 10)
sprintf(time,"0%d:0%d:0%d",hr,min,seconds);
else if(hr < 10 && min < 10)
sprintf(time,"0%d:0%d:%d",hr,min,seconds);
else if(hr < 10 && seconds < 10)
sprintf(time,"0%d:%d:0%d",hr,min,seconds);
else if(min < 10 && seconds < 10)
sprintf(time,"%d:0%d:0%d",hr,min,seconds);
else
sprintf(time,"%d:%d:%d",hr,min,seconds);
return time;
}
double floor(double var); Rounds down
double ceil(double var); Rounds up
These can be found in math.h