【问题标题】:Xcode - NSTimeInterval Years double value, how to get MORE decimals?Xcode - NSTimeInterval 年双值,如何获得更多小数?
【发布时间】:2013-01-13 16:58:15
【问题描述】:

我不知道 2 个 NSDate 之间到底有多少年。 (当前日期和日期选择器日期)

我正在使用 NSTimeInterval (seconds) 如何让它到几年?

此代码会将值设为 Years:

NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:date];

double secondsInAnYear = 31536000;
double YearsBetweenDates = distanceBetweenDates / secondsInAnYear;

NSString *dateString = [NSString stringWithFormat:@"%f", YearsBetweenDates];

labelView.text = dateString;

但我只得到 6 位小数!

我想要超过 6 位小数。怎么样?

【问题讨论】:

  • NSTimeIntervaltypedefdouble。看到这个问题:stackoverflow.com/questions/5729004/…
  • 谢谢!有用!我正在使用“%.20f”而不是“%f”。
  • 是否可以这样做:NSString *decimals =14;双 x =3.1415926535897932384626433; label.text = [NSString stringWithFormat:@"%%@f", x, decimals];这可以得到 14 位小数的 x 吗?
  • 一种方式:[NSString stringWithFormat:[NSString stringWithFormat:@"%%.%@f", decimals], x].

标签: iphone objective-c xcode nstimeinterval decimal


【解决方案1】:

看看-[NSCalendar (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts]。这样计算正确。您不能假设一年总是正好是 31536000 秒(闰年,甚至是偶尔添加的闰秒)。

【讨论】:

  • 这不会产生小数年份。只有整数:(
【解决方案2】:

您是否尝试过使用%lf,它是long float/double 值的指定说明符?

NSString *dateString = [NSString stringWithFormat:@"%lf", YearsBetweenDate];

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2012-08-14
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2016-10-04
    • 2013-02-14
    相关资源
    最近更新 更多