Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSDecimalNumber is whole number

What's the easiest way to check if an instance of NSDecimalNumber is a whole number?

Thanks!

like image 772
James Avatar asked Dec 11 '22 22:12

James


2 Answers

@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
like image 79
Jody Hagins Avatar answered Dec 14 '22 10:12

Jody Hagins


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!");
}
like image 33
yoninja Avatar answered Dec 14 '22 12:12

yoninja