Format a float value to get the digits before a decimal point
In my application I have a music player, which plays music with a length of 0:30 seconds.
However in a UILa开发者_开发百科bel I am currently displaying the progress, and as it is a float, the label is displaying i.e 14.765.
I would appreciate it if you could tell me how I could get the label to display
0:14 rather than 14.765.
Also, I would appreciate it if you could tell me how I could display 0:04 if the progress was 4seconds in.
This works properly:
float time = 14.765;
int mins = time/60;
int secs = time-(mins*60);
NSString * display = [NSString stringWithFormat:@"%d:%02d",mins,secs];
Results:
14.765 => 0:14
30.000 => 0:30
59.765 => 0:59
105.999 => 1:45
EDIT
In addition the 'one liner':
float time = 14.765;
NSString * display = [NSString stringWithFormat:@"%d:%02d",(int)time/60,(int)time%60];
You first need to convert your float
to an integer, rounding as you wish. You can then use the integer division, /
, and remainder, %
operations to extract minutes and seconds and produce a string:
float elapsedTime = 14.765;
int wholeSeconds = round(elapsedTime); // or ceil (round up) or floor (round down/truncate)
NSString *time = [NSString stringWithFormat:@"%02d:%02d", wholeSeconds/60, wholeSeconds%60];
The %02d
is the format specification for a 2-digits, zero padded, integer - look up printf
in the docs for full details.
//%60 remove the minutes and int removes the floatingpoints
int seconds = (int)(14.765)%60;
// calc minutes
int minutes = (int)(14.765/60);
// validate if seconds have 2 digits
NSString time = [NSString stringWithFormat:@"%i:%02i",minutes,seconds];
that should work. Can't test it i'm on Win currently
精彩评论