1

我想向我的用户收取他们使用服务的每小时或分数的 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]];

我究竟做错了什么?

4

1 回答 1

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.
于 2013-04-21T12:02:44.957 回答