如何获得NSNumber的正确值和类型?

How to get the correct value and type of NSNumber?

我正在通过使用 NSNumberFormatter 检查字符串是 float 还是 int 从字符串创建 NSNumber。我想要一种方法来 return NSNumber 持有什么类型和正确的值。它适用于 int,但不适用于十进制数。

NSNumber *n;
enum CFNumberType _numberType;

- (instancetype)initWithString:(NSString *)string {
    self = [super init];
    if (self) {
        NSNumberFormatter *formatter = [NSNumberFormatter new];
        decimalPattern = @"\d+(\.\d+)";
        if ([Utils matchString:string withPattern:decimalPattern]) {
            // Float
            formatter.numberStyle = NSNumberFormatterDecimalStyle;
            _numberType = kCFNumberDoubleType;
            n = [formatter numberFromString:string];
        } else {
            // Integer
            formatter.numberStyle = NSNumberFormatterNoStyle;
            _numberType = kCFNumberIntType;
            n = [formatter numberFromString:string];
        }
        self = [self initWithNumber:n];
    }
    return self;
}


- (CFNumberType)value {
    CFNumberType num;  // How to determine the type of num? 
    CFNumberGetValue((CFNumberRef)n, _numberType, &num);
    return num;
}

- (CFNumberType)numberType {
    return _numberType;
}

value方法中,如果我指定float num,那么它适用于浮点数。但我不能使用 float,因为我想让它也适用于 int。如何做到这一点?

我已经找到了解决办法。首先检查数字是否为 double 并调用适当的值方法。

- (BOOL)isDouble {
    if (_numberType == kCFNumberFloatType || _numberType == kCFNumberFloat32Type || _numberType == kCFNumberFloat64Type || _numberType == kCFNumberDoubleType) {
        return YES;
    }
    return NO;
}

- (double)doubleValue {
    if ([self isDouble]) {
        return [n doubleValue];
    }
    return 0.0;
}

- (int)intValue {
    if (![self isDouble]) {
        return [n intValue];
    }
    return 0;
}