AFNetworking小数点精度丢失问题

本问引自于:
关于iOS数据解析小数丢失精度的问题AFNetworking

目前发现

//出现BUG的条件是两位数或者一位数,且带两位小数,类型还必须是float//两位数:十位必须是7、8、9;个位数随意,一位数的个位数也必须是789//两位小数:第一位数随意;第二位数必须是

下面是正常请求。

 NSURLSessionDataTask*task = [manager POST:httpStr parameters:secureDic progress:nilsuccess:^(NSURLSessionDataTask* _Nonnull task, id  _Nullable responseObject) {  
        //请求回来打印responseObject  
       if(!isRedirect) {  
           [selfsaveCookies];  
           requestBlock(responseObject,nil);  
       }  
        
    } failure:^(NSURLSessionDataTask* _Nullable task, NSError* _Nonnull error) {  
        if(![DataRequest haveInternet]) {  
               
            NSDictionary*mesDic = @{@"mes":DataRequestNoInternetMessage};  
            NSDictionary*notWorkDic = @{@"message":mesDic};  
            requestBlock(notWorkDic,nil);  
               
        }else  
            requestBlock(dic,nil);  
    }];

打印结果如下,discount字段,服务器返回的是double,9.70,AFNetworking解析后就成了9.699999999999

AFNetworking小数点精度丢失问题_第1张图片

后来查了下,发现是苹果的json解析会莫名其妙丢失精度

以下是测试结果

以下是测试结果   
NSString *jsonStr = @"{\"9.70\":9.70, \"97.40\":97.40, \"80.40\":80.40, \"188.40\":188.40}";
    NSLog(@"json:%@", jsonStr);
    NSData *jsonData_ = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *jsonParsingError_ = nil;
    NSDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:jsonData_ options:0 error:&jsonParsingError_]];
    NSLog(@"dic:%@", dic);
    /*结果:dic:{
     "188.40" = "188.4";
     "80.40" = "80.40000000000001";
     "9.70" = "9.699999999999999";
     "97.40" = "97.40000000000001";
     }*/

解决办法:

NSString *decimalNumberWithDouble(double conversionValue){  
    NSString *doubleString        = [NSString stringWithFormat:@"%lf", conversionValue];  
    NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];  
    return [decNumber stringValue];  

你可能感兴趣的:(AFNetworking小数点精度丢失问题)