Pergunta

I'm using SBJSON in a project and I'm trying to build a json string from a dictionary.

Here's what's going on, I'm putting floats as NSNumbers into a dictionary:

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];

And then to finally write it as a json string, I tried these three.

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];

Each of these changes 0.95 into 0.95000000000000034355 or even worse 0.949999999999999992344 or something alike.

Why is this happening? How can I prevent this? Thanks

Foi útil?

Solução

That's the basic problem with float values. You can't store values which can't be represented by the sum of the power of 2. Thus resulting with the approximate value to your floating point.

e.g. 1.25 can be easily represented as sum of power of 2
i.e. 1*2^0 +1*2^-2 but if you are going to represent 1.33 as sum of power of 2 then the resultant would be 1*2^0 + 1*2^-2 + 1*2^-4 + 1*2^-8 + 1*2^-9 ....

Just read Representable numbers, conversion and rounding on wiki.
And you can check your floating point representation using online tool.

Outras dicas

This is the classic problem with floating point numbers. You can, however, use NSDecimalNumber rather than NSNumber to get higher precision (at the cost of lower range of numbers).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top