代码之家  ›  专栏  ›  技术社区  ›  Aleph72

四舍五入一个并不总是按预期工作的数字

  •  1
  • Aleph72  · 技术社区  · 13 年前

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

    我做错了什么?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Sergey Kalinichenko    13 年前

    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.
    
    推荐文章