OC、swift数据JSON序列化后,浮点型数据丢失的问题
出现的问题:服务后端定义的数据类型为float、double时,前端进行序列化时数据精度丢失。
要么在后端处理,定义为string类型。要么在前端处理,将float、double转化为string!!
注意:在序列化前调用此方法!!
+ (NSString *)doubleConvertString:(NSString *)source
{
NSString *targetStr = [NSString stringWithFormat:@"%@",source];
if (source.length == 0)
{
return targetStr;
}
NSUInteger index = 0;
NSString *p = [targetStr substringToIndex:1];
NSString *rStr = p;
NSString *lChar = p;
NSString *llid = nil;
BOOL inserted = false;
NSArray *tarry = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
while (index < targetStr.length-1)
{
index++;
NSString *currChar = [targetStr substringWithRange:NSMakeRange(index, 1)];
BOOL cf = [tarry containsObject:currChar];
if ([lChar isEqualToString: @":"] && cf && [llid isEqualToString:@"\""])
{
inserted = true;
rStr = [rStr stringByAppendingString:@"\""];
llid = @"";
}
else if (inserted && ([currChar isEqualToString: @"}"] || [currChar isEqualToString: @","]))
{
inserted = false;
rStr = [rStr stringByAppendingString:@"\""];
}
rStr = [rStr stringByAppendingString:currChar];
if (currChar.length > 0 && ![currChar isEqualToString:@" "])
{
if ([currChar isEqualToString:@"\""])
{
llid = currChar;
}
else if (![currChar isEqualToString:@":"])
{
llid = @"";
}
lChar = currChar;
}
}
return rStr;
}