将float 1.88转换为字符串HH:MM

问题描述 投票:-4回答:1

我想在调整自定义滑块时在UILabel上显示HH:MM。目前我的自定义滑块返回浮动值,例如2.89,24.87 ......我希望将浮点值设为24.87并将其更改为24:52我在下面的代码中得到了所有工作但我认为它不是最有效的方式。任何人都可以改善吗?谢谢

- (void)slideValueChanged:(id)control
{
    NSLog(@"Slider value changed: (%.2f,%.2f)",
      _rangeSlider.lowerValue, _rangeSlider.upperValue);

    lblStart.text = [NSString stringWithFormat:@"Start Time : %@", [self floatToTime:_rangeSlider.lowerValue]];
    lblEnd.text = [NSString stringWithFormat:@"End Time : %@",[self floatToTime:_rangeSlider.upperValue]];

} 

- (NSString*)floatToTime:(float)floatTime {

    NSInteger iHour = floatTime;
    CGFloat floatMin = floatTime - iHour;

    NSString *sHour = [NSString stringWithFormat:@"%li", (long)iHour];

    if (floatMin == 0.99) {  //=== When the float is 0.99, convert it to 0, if not 60*0.99 = 59.4, will never get to 0
        floatMin = 0;
    }else{

        floatMin = floatMin * 60;
    }

    NSInteger iMin = floatMin; //=== Take the integer part of floatMin

    NSString *sMin = [[NSString alloc] init];
    if (iMin <10){ //=== Take care if 0,1,2,3,4,5,6,7,8,9 to be 00,01,02,03...
        sMin = [NSString stringWithFormat: @"0%li", iMin];
    }else{
        sMin = [NSString stringWithFormat: @"%li", iMin];
    }

    NSString *strFloatTime = [NSString stringWithFormat:@"%@:%@", sHour,sMin];
    return strFloatTime;
}
ios objective-c time
1个回答
1
投票

您可以使用格式显示两位数,这简化了创建时间字符串的过程:

CGFloat time = 24.87;
int hours = fabs(time);
int minutes = (int)((time - hours) * 60.0);
NSLog(@"Time: %02d:%02d", hours, minutes);

结果:“时间:24:52”

'02'是位数。

© www.soinside.com 2019 - 2024. All rights reserved.