views:

80

answers:

1

Are there equivalent methods for ceilf and floorf for the NSDecimalNumber type? I couldn't seem to find any.

+4  A: 

Simple solution: You can get the float value of the number object and call ceilf() or floorf():

ceilf([decimalNumber floatValue]);

Otherwise, you can use the – decimalNumberByRoundingAccordingToBehavior: method.

First you'll need to implement the NSDecimalNumberBehaviors protocol for each rounding mode you want to use:

@interface DecimalRounder : NSObject <NSDecimalNumberBehaviors> { }
@end

@implementation DecimalRounder

- (NSRoundingMode)roundingMode {
    return NSRoundUp;
}

- (short)scale {
    return 0;
}

@end

And then (assuming your decimal number is 12.5):

DecimalRounder *rounder = [[DecimalRounder alloc] init];
NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithFloat:12.5];
NSDecimalNumber *roundedNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:rounder];
NSLog(@"decimalNumber: %@", decimalNumber);
NSLog(@"roundedNumber: %@", roundedNumber);

You'll get:

decimalNumber: 12.5
roundedNumber: 13
fjoachim
I went with the second option because the conversion to float (or double) loses precision.
rein