Question

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

How can I round up this double so that there are only 2 digits left after the "dot"?
It would be very good if the result is a NSNumber.

Was it helpful?

Solution

If this is for display purposes, take a look at NSNumberFormatter.

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

OTHER TIPS

A NSDecimal can be rounded to a specified number of digits with NSDecimalRound().

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

NSDecimalNumber *result = [NSDecimalNumber decimalNumberWithDecimal:out];

If you really want two digits left after the dot, multiply by 100, round it using round() function, divide it by 100 again. However, this will not guarantee that it really has only two digits after the dot, since by dividing it again, you may get a number that cannot really be expressed with floating point notation and when you expect 0.1 you may in fact get 0.09999..., that's because you cannot really express 0.1 using floating point notation.

If you just want to round it to two digits after the dot for display purposes, you can use NSNumberFormatter as has been suggested or just use:

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

or to get an NSString, you can also use the following, which is probably even faster than using a NumberFormatter (however, it won't be localized according to the user prefs):

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

In the vast majority of cases rounding a number is something you should only do at display time. The properties of floating-point numbers (double or not) make it impossible to store certain numbers at a fixed-precision.

For information about formatting a number so it displays to two decimal places, see this other post.

Does this HumanReadableTimeInterval help? It returns a NSString, though. Alternatively, you can round yourself by multiplying with 100, converting to an integer and dividing through 100 again.

I would just use the ANSI C round() function.

You can always round the number using:

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

But chances are that the representation of the result as a double will not have only 2 decimals.

Now, if by using the == sign, you meant that the comparison of your two double numbers is made only to the second decimal. Here is what you can do:

fabs(round2dec(NSTimeInterval) - round2dec(double)) < std::numeric_limits<double>::epsilon()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top