How to compare two NSDecimalNumber values
Posted: | Author: Jörn | Filed under: iOS, Objective-C | Tags: Compare, NSDecimalNumber, NSNumber | No Comments »Recently I had to use NSDecimalNumber objects to avoid the rounding errors that come with float values. While comparing two float values is as easy as it gets comparing two NSDecimalNumbers works a bit different:
NSDecimalNumber is a subclass of NSNumber so you have to use NSNumber’s compare: method to compare the values:
NSDecimalNumber *number1 = [NSDecimalNumber numberWithFloat:0.1];
NSDecimalNumber *number2 = [NSDecimalNumber numberWithFloat:0.2];
// check if number1 is less than number2
if ([number1 compare:number2] == NSOrderedAscending {
NSLog(@"number1 is less than number2")
}
Leave a Reply