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.
This is a discussion on Float to Int within the C Programming forums, part of the General Programming Boards category; I imagine this is quite simple, probably no more complicated than a cast. Anyway how do you convert a float ...
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.
PuterPaul.co.uk - Portfolio site
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);
All spelling mistakes, syntatical errors and stupid comments are intentional.
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; }
Last edited by pdstatha; 03-30-2002 at 07:09 AM.
PuterPaul.co.uk - Portfolio site
double floor(double var); Rounds down
double ceil(double var); Rounds up
These can be found in math.h
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.