views:

25

answers:

4

I am trying to parse a json value to a decimal with no success. I am using the following framework

http://code.google.com/p/json-framework/

and my code is as follows

NSDecimal RRP = [[jProduct objectForKey:@"Price"] decimalValue];
NSLog(@"%@", RRP);

I get

Program received signal: “EXC_BAD_ACCESS”.

Just to test I thought I would try this:

NSLog(@"%@", [jProduct objectForKey:@"Price"]);

42.545

I get the value but obviously I have not set the NSDecimal.

Anybody else had similar experince or can see what I am doing wrong?

Thanks

A: 
[jProduct objectForKey:@"Price"]

may be a NSString. NSString respond to:

 – doubleValue
 – floatValue
 – intValue
 – integerValue
 – longLongValue
 – boolValue

not decimalValue

Verify the class of your data.

Benoît
+1  A: 

I'm not familiar with the framework you are using but I would suggest the following:

What is the type returned by [jProduct objectForKey:@"price"]?

You probably need to work around the fact that this is the wrong type - maybe a an NSString?

Try:

NSDecimal RRP = [[NSDecimalNumber decimalNumberWithString:[jProduct objectForKey:@"Price"] decimalValue];

Edit:

Oh and NSDecimal is a struct, not an object so you shouldn't be using NSLog(@"%@"); as the %@ format identifier is for objects.. Instead you can use the basic type format identifiers such as %d or %i and access the components of the structure individually.

However, as you probably want to log a decimal rather than the components of the struct (sign, mantissa etc) then you will probably want to convert it back to an NSDecimalNumber (which is an object).

So it becomes:

NSLog(@"%@", [NSDecimalNumber decimalNumberWithDecimal:RRP]);

mikecsh
Right: `NSDecimal` is not an object; you can't use `%@` to print it.
Wevah
A: 

store the value in NSNumber

NSNumber *num = [jProduct objectForKey:@"Price"];

xCode
NSNumber stores values binary, not in decimal so this will code will cause a loss of accuracy.
mikecsh
A: 

An NSDecimal is a struct, not an object. If you want to print an NSDecimal, use NSDecimalString():

NSDecimal rrp = [[jProduct objectForKey:@"Price"] decimalValue];
NSLog(@"%@", NSDecimalString(rrp));
Wevah