Cheng Cheng - 4 months ago 19
iOS Question

iOS - Decimal Value Changed After Converting a JSON String Into a JSON Object

I get data from my Background

NSString * jsonStr = data[@"result"];
NSData * jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];


This is the JsonStr:

{"id":2,"name":"轮胎式起重机","brand":"中联","type":"QY130","weight":130.0,"isValid":"1","ext1":65.9,"ext2":34.6,"ext3":100.6,"ext4":75.0,"ext5":65805.0,"createTime":"2016-07-20 10:58:09"}


In JsonStr the value for @"ext1" is 65.9, but after jsonobject the value become '65.90000000000001'

This is the dic:

{
brand = "\U4e2d\U8054";
createTime = "2016-07-20 10:58:09";
ext1 = "65.90000000000001";
ext2 = "34.6";
ext3 = "100.6";
ext4 = 75;
ext5 = 65805;
id = 2;
isValid = 1;
name = "\U8f6e\U80ce\U5f0f\U8d77\U91cd\U673a";
type = QY130;
weight = 130;


}

What's wrong with this data?

Answer

When you use ext1 as NSNumber:

NSNumber *ext1 = @([dic[@"ext1"] floatValue]);
NSLog(@"%@", ext1);

It will be 65.9.

NSString:

NSString *ext1Str = [NSString stringWithFormat:@"%@",ext1];
NSLog(@"%@", ext1Str);

2016-08-01 13:19:46.969 OCDemo[2200:78063] 65.9 2016-08-01 13:19:46.970 OCDemo[2200:78063] 65.9

Comments