如何检查IOS中的数字是NSInteger还是浮点数?
问题描述:
我需要检查来自服务器的值是NSString,NSInteger还是float.如果是字符串,我可以检查.但是如何区分浮点数和整数呢?
I need to check whether a value which is coming from the server is NSString , NSInteger or float. In case of string i am able to check.But how can we differentiate between a float and integer ?
答
此处是操作方法
NSNumber * n = //from somewhere
if (strcmp([n objCType], @encode(float)) == 0) {
NSLog(@"this is a float");
} else if (strcmp([n objCType], @encode(int)) == 0) {
NSLog(@"this is an int");
}
编辑
好的,让我们更通用
NSNumber *anyNSObject = [NSNumber numberWithFloat:0.4];
id obj = anyNSObject; //you can pass anything here as long as it is inherited from NSObject
if ([obj isKindOfClass:[NSString class]]) {
NSLog(@"This is string");
}
if ([obj isKindOfClass:[NSNumber class]]) {
NSLog(@"This is NSNumber");
if (strcmp([obj objCType], @encode(float)) == 0) {
NSLog(@"this is a float");
} else if (strcmp([obj objCType], @encode(int)) == 0) {
NSLog(@"this is an int");
}
}