我在一个项目中使用 SBJSON,我正在尝试从字典中构建一个 json 字符串。
这是发生了什么,我将浮点数作为 NSNumbers 放入字典中:
NSDictionary* tempdic = [[NSDictionary alloc] init];
tempdic = [NSDictionary dictionaryWithObjectsAndKeys:productId, @"productId", [NSNumber numberWithFloat:quantity], @"aantal", price, @"price" , nil];
[orders addObject:tempdic];
NSDictionary* json = [NSDictionary dictionaryWithObjectsAndKeys: orders, @"order", message, @"message", [NSNumber numberWithFloat:orderprice], @"totalPrice",dueDate,@"dueDate", nil];
然后最后把它写成一个 json 字符串,我尝试了这三个。
1)
NSData* jsonData = [writer dataWithObject:json];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
2)
NSString* jsonString = [json JSONRepresentation];
3)
NSString* jsonString = [writer stringWithObject:json];
这些中的每一个都将 0.95 更改为 0.95000000000000034355 或更糟糕的 0.9499999999999999992344 或类似的东西。
为什么会这样?我怎样才能防止这种情况?谢谢