开发者

ceilf and floorf equivalent methods for NSDecimalNumber

Are there equivalent methods for ceilf and floorf for th开发者_高级运维e NSDecimalNumber type? I couldn't seem to find any.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜