NSTimeInterval for reading NSNumber

NSTimeInterval == double; (e.g. 169.12345666663)

How can I round this double so that only 2 digits remain after the “dot”?
It would be very nice if the result is NSNumber.

+3
source share
7 answers

If it is intended for viewing, look at NSNumberFormatter .

If you really want to round the double in your calculations for any reason, you can use the standard C function round().

+6
source

. NSDecimal NSDecimalRound().

double d = [[NSDate date] timeIntervalSince1970];
NSDecimal in = [[NSNumber numberWithDouble:d] decimalValue];
NSDecimal out;
NSDecimalRound( &out, &in, 2, NSRoundUp );

NSDecimalNumber *result = [NSDecimalNumber decimalNumberWithDecimal:out];
+2

, , 100, , round(), 100. , , , , , , 0.1, 0.09999..., 0,1, .

, NSNumberFormatter, :

printf("%.2f\n", yourTimeInterval);
NSLog(@"%.2f\n", yourTimeInterval);

NSString , , , , NumberFormatter ( ):

NSString * intervalStr = nil;
char * intervalStrTmp = NULL;
asprintf(&intervalStrTmp, "%.2f", yourTimeInteval);
if (intervalStrTmp) {
  intervalStr = [[NSString alloc] initWithUTF8String:intervalStrTmp];
  free(intervalStrTmp);
}
+2

HumanReadableTimeInterval? NSString. , 100, 100.

+1

- , . ( ) .

, , . .

+1

ANSI C round().

0

, :

double round2dec(double a) { return round(a * 100) / 100; }

, 2 .

, == , . :

fabs(round2dec(NSTimeInterval) - round2dec(double)) < std::numeric_limits<double>::epsilon()
0

All Articles