ios 判断字典中的数据类型

ios网络请求多数用json格式,数据解析之后的NSDictionary中的数据类型只有断点以后的控制台或者po出来查看,

代码上如何处理各种数据类型的

+(NSString*)fromTypeToString:(id)data{

// 判断是不是数字类型

    NSNumber *myNumber  = (NSNumber *)data;

    int minThreshold = [myNumber intValue];

    if ((int)minThreshold < 1 )

    {

        NSLog(@"不是数字");

    }

    else{

//  对于各种数字类型的  处理

        if (strcmp([myNumber objCType], @encode(BOOL)) == 0) { // 布尔值

            returnString = @"BOOL";

            NSLog(@"this is a bool");

        } else if (strcmp([myNumber objCType], @encode(int)) == 0) { // int 类型

            returnString = @"int";            

            NSLog(@"this is an int");

        }

        else if (strcmp([myNumber objCType], @encode(float)) == 0) { // float 类型

            returnString = @"float";

            NSLog(@"this is an float");

        }

        else if (strcmp([myNumber objCType], @encode(double)) == 0) { // double 类型

            returnString = @"double";

            NSLog(@"this is an double");

        }

}

关于 double 类型  精度丢失 的问题解决

double conversionValue =  [[data[@"double"] stringValue] doubleValue];

NSString *doubleString = [NSString stringWithFormat:@"%lf", conversionValue];   

NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];

 return [decNumber stringValue];


//直接传入精度丢失有问题的Double类型  后台数据 0.01   有的时候接到的却是  0.009999999999 这类的

+ (NSString *)reviseString:(NSString *)str

{

    double conversionValue = [str doubleValue];

    NSString*doubleString = [NSString stringWithFormat:@"%lf", conversionValue];

    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];

    return [decNumber stringValue];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容