Server data accuracy is lost

When the back-end server returns data to float / double type when, OC reception will be .0000001 precision loss problem, find information there was said to be NSNumber description of the method is not precise enough, according to when calling the loss of precision.

Solution:

1, so that a unified server returns a String data type

2, we deal with on their own. When the server returns a float / double type, the use of precision processing solutions NSDecimalNumber loss problems

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

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

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

 

Project I am using MJExtension model transformation objects, find MJPropertyKey.m file, modify valueInObject: method,

- (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;
}

 

Guess you like

Origin blog.csdn.net/maolianshuai/article/details/88391771