检查实例NSDecimalNumber
是否为整数的最简单方法是什么?
谢谢!
@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
从十进制数中减去整数。如果差为零,则十进制数是整数。
// testVal is NSDecimalNumber
NSString *test = [testVal stringValue];
int intVal = [test intValue];
double doubleVal = [test doubleValue];
if(doubleVal-intVal == 0){
NSLog(@"Whole number!");
}
或者,获取整数并与原始值进行比较:
if(intVal == doubleVal){
NSLog(@"Whole number!");
}
这应该有效。
谨防使用转换NSDecimalNumber
为double
.
NSDecimalNumber* input = [...];
NSDecimal roundedDecimal;
NSDecimalRound(&roundedDecimal, [input decimalValue], 0, NSRoundPlain);
NSDecimalNumber* roundedNumber = [NSDecimalNumber decimalNumberWithDecimal:roundedDecimal];
BOOL inputIsWholeNumber = [input isEqualToNumber:roundedNumber];
您还应该检查NaN
值。
你能不使用 if ((number % 1) == 0)
@implementation NSDecimalNumber (isWholeNumber)
-(BOOL)isWholeNumber
{
double x = [self doubleValue]; //The approximate value of the receiver as a double.
double y = floor (x);
if(fabs(x - y) < DBL_EPSILON)
return YES;
return NO;
}
@end
// [myDecNumber isWholeNumber];
不知道为什么,但由于某种原因,我无法让 Jody Hagins 或 Sulthan 的解决方案发挥作用,所以我采取了稍微不同的方式:
-(BOOL)isWholeNumber:(NSDecimalNumber *)number {
NSDecimalNumber *input = number;
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:0
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
NSDecimalNumber *vOne = [NSDecimalNumber decimalNumberWithString:@"1"];
NSDecimalNumber *result = [number decimalNumberByMultiplyingBy:vOne
withBehavior:handler];
BOOL inputIsWholeNumber = [input isEqualToNumber:result];
return inputIsWholeNumber;
}
试试这个,你可以跳过第一行,我只是用它来创建一个 NSDecimalNumber 对象
NSDecimalNumber *decNumb=[NSDecimalNumber decimalNumberWithString:@"20.5"];//try with just 20
NSString* str=[NSString stringWithFormat:@"%@",decNumb];
if ([str rangeOfString:@"."].location==NSNotFound && [str rangeOfString:@"-"].location==NSNotFound) {
NSLog(@"it is whole number");
}
else
NSLog(@"it is not whole number");