iOS接口数据解析问题

由于iOS API的原因,接口解析数据是存在一个缺陷,下面将具体讲述。

1、问题描述##

如果后台所传数据是Decimal类型,则解析出的数据在精确度上会存在一定的问题。

{ 
  Environment = Both;
  "Ground_indoor" = Finished;
  "Ground_outdoor" = Finished; 
  "Max_Working_Height" = "9.800000000000001"; 
  Name = "8m Battery Scissor Lift - Genie GS2632"; 
  "Non_Marking_Tyres" = 1; 
  "Platform_Length" = "2.26"; 
  "Platform_Type" = "Scissor Lift"; 
  "Platform_Width" = "0.8100000000000001";
   "Tax_Class" = E; Weight = 1956;
}

可以发现这段数据里有两个数据出现了问题,其实接口传过来的只是“9.8”和“0.81”。

2、问题解释##

Or if that is too much to read, let's simply put it this way - for example, let's take the value 0.81 as an example. The number cannot be accurately represented by a float and is rounded up to 0.8100000000000001 because an int value of 81 is represented by the binary value 1010001. In order to make the value 0.81 it would be accurate if you could take 81 x 10^-2 (= 81 / 10^2.) But that’s impossible because you must use the base 2 instead of 10. So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 81 (1010001) + 3 bits for the value 7 (111). Then the value 81 x 2^-7 is not seriously inaccurate. So to improve this inaccuracy, we could change the value 81 and 7 to something else. So the formula for your value would be X = A x 2^B where A and B are integer values positive or negative. The higher the numbers are the higher accuracy become. However as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

以上是比较完整的解答,简而言之就是iOS将接口数据先解析为二进制数,然后再转成float展示。特别是针对小数会出现这种问题。

3、解决方案##

将接口数据以字符串的形式传给移动端,这种方法是最有效的。

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:dataDict[@"Total"]]);

这种方法相对繁琐一点。

你可能感兴趣的:(iOS接口数据解析问题)