Domanda

I found an interesting question what's not described on the internet, even is misleading in the apple documentation. What are the differences between:

kCFNumberFormatterRoundCeiling

kCFNumberFormatterRoundFloor

kCFNumberFormatterRoundDown

kCFNumberFormatterRoundUp

kCFNumberFormatterRoundHalfEven

kCFNumberFormatterRoundHalfDown

kCFNumberFormatterRoundHalfUp

?

kCFNumberFormatterRoundCeiling explanation is equal with kCFNumberFormatterRoundUp but they are not working the same, the same case in kCFNumberFormatterRoundFloor and kCFNumberFormatterRoundDown

È stato utile?

Soluzione

The documentation is indeed ambigous. Both kCFNumberFormatterRoundFloor and kCFNumberFormatterRoundDown are documented as

Round down to next larger number with the proper number of fraction digits.

A small test shows that these rounding modes give different results for negative numbers.

kCFNumberFormatterRoundFloor behaves similar to the floor() function. It rounds always to a smaller (or equal) value. On the other hand kCFNumberFormatterRoundDown rounds "towards zero", i.e. it returns gives a number whose absolute value is smaller or equal to the absolute value of the input.

Example: (using NSNumberFormatter)

NSNumberFormatter *f1 = [[NSNumberFormatter alloc] init];
[f1 setMaximumFractionDigits:0];
[f1 setRoundingMode:NSNumberFormatterRoundFloor];

NSNumberFormatter *f2 = [[NSNumberFormatter alloc] init];
[f2 setMaximumFractionDigits:0];
[f2 setRoundingMode:NSNumberFormatterRoundDown];

double x = -1.5;
NSLog(@"%@, %@", [f1 stringFromNumber:@(x)], [f2 stringFromNumber:@(x)]);
// Output: -2, -1

x = + 3.5;
NSLog(@"%@, %@", [f1 stringFromNumber:@(x)], [f2 stringFromNumber:@(x)]);
// Output: 3, 3

Similarly, kCFNumberFormatterRoundCeiling returns a value that is larger or equal to the input (like ceil()), and kCFNumberFormatterRoundUp rounds "away from zero".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top