Comparing NSDecimalNumber won't work?
Asked Answered
A

1

5

For some reason, the comparing logic isn't working correctly... it wont compare two NSDecimalNumber objects. Sometimes it works, sometimes it doesn't. Really weird. The if statement works on some compilations, and sometimes not. Is this the right way of doing it?

The data is from a json file which is a 2 point decimal number which looks like this: 63.32

Why isn't this working correctly?

NSError * error;
    NSDictionary * json = [NSJSONSerialization JSONObjectWithData:responceData options:kNilOptions error:error];
    NSArray * latestPrice = [json objectForKey:@"data"];
    NSLog(@"Latest price %@", latestPrice);

    NSNumber * value = [(NSDictionary*)[latestPrice objectForKey:@"last_offer"] objectForKey:@"display"];

    NSString * val = [[NSString alloc] initWithFormat:@"%@", value];
    NSString * valFinal = [val stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:valFinal];
    NSLog(@"%@", number);
    NSString * val2 = [[NSString alloc] initWithString:@"44.14"];
    NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:val2];
    if(number2 >= number){
    NSLog(@"ds");
    }

I need to compare the json value with a local value with the same decimal points.

Andraandrade answered 30/3, 2013 at 0:52 Comment(1)
An NSDecimalNumber is an object. You're comparing addresses. Read the spec for the class to see how to compare.Smolensk
L
7

NSDecimalNumber is an object. You tried to compare memory addresses.
Use compare: instance method of NSDecimalNumber.

if ([number compare:number2] == NSOrderedAscending)

NSDecimalNumber Class Reference

Lakitalaks answered 30/3, 2013 at 1:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.