Objective-C:如何将浮点值格式化为仅显示十进制,没有完整图形或小数点?

时间:2014-05-05 14:24:53

标签: objective-c time cocos2d-iphone floating-point

有很多Q& A用于限制只有2个小数位,到达过饱和点。

但是,我想将我的浮点格式化为仅获取小数值。

我正在制作秒表,目前有这个......

@implementation HudLayer
{
    CCLabelTTF *_label; 
    float timer;
}

-(void)update:(ccTime)delta { if (_isTimerActive)
    {
        timer += delta;

        NSNumber *theDouble = [NSNumber numberWithDouble:timer];
        float miliseconds = timer;
        int inputSeconds = [theDouble intValue];
        int hours =  inputSeconds / 3600;
        int minutes = ( inputSeconds - hours * 3600 ) / 60;
        NSString *theTime = [NSString stringWithFormat:@"%.2d:%.2d:%.2f", hours, minutes, miliseconds];

        [_label setString:[NSString stringWithFormat:@"Time: %@", theTime]];
    }
}

然而,我遇到的问题是计时器读出显示完整秒数的标签......

00:14:865.35

相反它应该只是:

00:14:05.35

HH:MM:SS.ms

我的第一个想法是从输出的浮点数中删除小数点,并按小时和分钟手动计算秒数...

有什么建议吗?感谢...

1 个答案:

答案 0 :(得分:0)

尝试以下

timer += delta;

float float_seconds = timer;
int seconds = float_seconds;
int hours = seconds / 3600;
int minutes = seconds / 60 % 60;
NSString *theTime = [NSString stringWithFormat:@"%.2d:%.2d:%05.2f", hours, minutes, float_seconds - ( seconds / 60) * 60];
NSLog(theTime);

[_label setString:[NSString stringWithFormat:@"Time: %@", theTime]];