服务器数据精度丢失

当后台服务器返回数据为float/double类型时,OC接收会出现.0000001精度丢失问题,经查找资料有说是NSNumber的description方法不够严谨,调用时照成的精度丢失。

解决办法:

1、让服务器统一返回String类型数据

2、我们自行处理。当服务器返回float/double类型时,利用NSDecimalNumber处理解决精度丢失问题

NSString *value = [NSString stringWithFormat:@"%lf", 服务器数据.doubleValue];

NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithString:value];

NSLog(@"%@", decimalNumber.stringValue);

项目中我使用的是MJExtension模型转换对象,找到 MJPropertyKey.m文件,修改valueInObject:方法,

- (id)valueInObject:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]] && self.type == MJPropertyKeyTypeDictionary) {
        
        NSString *value = [NSString stringWithFormat:@"%@", object[self.name]];
        NSScanner *scan = [NSScanner scannerWithString:value];
        float f;
        double d;
        // 判断value是否为浮点型数据
        if (([scan scanFloat:&f] && [scan isAtEnd]) || [scan scanDouble:&d] && [scan isAtEnd])
        {
            value = [NSString stringWithFormat:@"%lf", [object[self.name] doubleValue]];
            // NSDecimalNumber接收
            NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithString:value];
            return decimalNumber.stringValue;
        }
        
        return object[self.name];
    } else if ([object isKindOfClass:[NSArray class]] && self.type == MJPropertyKeyTypeArray) {
        NSArray *array = object;
        NSUInteger index = self.name.intValue;
        if (index < array.count) return array[index];
        return nil;
    }
    return nil;
}

猜你喜欢

转载自blog.csdn.net/maolianshuai/article/details/88391771
今日推荐