Ios6 将数字四舍五入并不总是如预期的那样有效

Ios6 将数字四舍五入并不总是如预期的那样有效,ios6,rounding-error,rounding,Ios6,Rounding Error,Rounding,我想为我的用户使用服务的每小时或分数收取1个积分。 为了计算成本,我使用了以下代码,但在某些情况下,例如,当开始和结束日期正好相差一天时,我得到的成本是25学分,而不是24学分: NSNumberFormatter *format = [[NSNumberFormatter alloc]init]; [format setNumberStyle:NSNumberFormatterDecimalStyle]; [format setRoundingMode:NSNumberFormatterRou

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

我做错了什么?

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.

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.

我试过你的代码,但它没有按我的预期工作。例如,如果开始日期是今天下午4:00,结束日期是今天下午4:02,则不计算1学分。同样,如果差值是1小时,比如说3分钟,那么只算1学分。@Aleph72您可以使用这个技巧对整数除法进行取整(请参见编辑)。好的,这个技巧有效。但我不明白为什么。你能解释一下吗?我说得太早了。如果日期差正好是24小时,我会得到25学分…顺便说一下,这两个日期是从UIDatePicker获取的,我不知道这是否会改变什么。我已经尝试了你的代码,但它没有按我的预期工作。例如,如果开始日期是今天下午4:00,结束日期是今天下午4:02,则不计算1学分。同样,如果差值是1小时,比如说3分钟,那么只算1学分。@Aleph72您可以使用这个技巧对整数除法进行取整(请参见编辑)。好的,这个技巧有效。但我不明白为什么。你能解释一下吗?我说得太早了。如果日期差正好是24小时,我会得到25学分…顺便说一句,这两个日期是从UIDatePicker处获取的,我不知道这是否会改变什么。