我想向用户收取每小时1个积分,或者他们使用服务的分数。 要计算我使用以下代码的成本,但在某些情况下,例如当开始和结束日期恰好是一天的差异时,我得到的是25个学分而不是24个学分:
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundUp];
[format setMaximumFractionDigits:0];
[format setMinimumFractionDigits:0];
NSTimeInterval ti = [endDate timeIntervalSinceDate:startDate];
float costValue = ti/3600;
self.cost = [format stringFromNumber:[NSNumber numberWithFloat:costValue]];
我做错了什么?
答案 0 :(得分:1)
NSTimeInterval
具有亚毫秒精度。如果日期分别为一天和一毫秒,您将收取第25个学分。
更改代码进行整数除法应该解决问题:
// You do not need sub-second resolution here, because you divide by
// the number of seconds in the hour anyway
NSInteger ti = [endDate timeIntervalSinceDate:startDate];
NSInteger costValue = (ti+3599)/3600;
// At this point, the cost is ready. You do not need a special formatter for it.