What's the easiest way to check if an instance of NSDecimalNumber
is a whole number?
Thanks!
@interface NSDecimalNumber (IsIntegerNumber)
@property (readonly) BOOL isIntegerNumber;
@end
@implementation NSDecimalNumber (IsIntegerNumber)
-(BOOL)isIntegerNumber {
NSDecimalValue value = [self decimalValue];
if (NSDecimalIsNotANumber(&value)) return NO;
NSDecimal rounded;
NSDecimalRound(&rounded, &value, 0, NSRoundPlain);
return NSDecimalCompare(&rounded, &value) == NSOrderedSame;
}
@end
Subtract the whole number from the decimal number. If the difference is zero then the decimal number is a whole number.
// testVal is NSDecimalNumber
NSString *test = [testVal stringValue];
int intVal = [test intValue];
double doubleVal = [test doubleValue];
if(doubleVal-intVal == 0){
NSLog(@"Whole number!");
}
Or, get the whole number and compare to the original value:
if(intVal == doubleVal){
NSLog(@"Whole number!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With