-1

Im dealing with currency values that I need to subtract from each other. I read that NSNumber is good for dealing with currency, however I am unable to subtract two NSNumbers. Is there a better way for dealing with currencys or am I missing something small?

 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
        NSNumber* number = [numberFormatter  numberFromString:bDict[@"booking_deposit"]];
        if (!number) {
            [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
            number = [numberFormatter  numberFromString:bDict[@"booking_deposit"]];
        }
        NSNumber* number2 = [numberFormatter  numberFromString:bDict[@"booking_total"]];
        if (!number2) {
            [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
            number2 = [numberFormatter  numberFromString:bDict[@"booking_total"]];
        }
        NSLog(@"result %@",number2 - number);//warning here

And heres the warning:

Arithmetic on pointer to interface 'NSNumber', which is not a constant size for this architecture and platform
DevC
  • 6,982
  • 9
  • 45
  • 80
  • `NSNumber` provides nothing other than wrapping primitive number types for storage within Objective-C collection classes. Also attempting to subtract two objects using `-` indicates that you don't understand how objects work (or you assume operator overloading). – trojanfoe May 15 '15 at 12:09
  • @trojanfoe thanks how would you go about dealing with currency? – DevC May 15 '15 at 12:10
  • 1
    See [this question](http://stackoverflow.com/questions/421463/should-i-use-nsdecimalnumber-to-deal-with-money). – trojanfoe May 15 '15 at 12:11

2 Answers2

2

You need to get the type of value you stored in the NSNumber out to preform arithmetic.

NSLog(@"result = %f", [number2 doubleValue] - [number doubleValue])
Tobias
  • 4,397
  • 3
  • 26
  • 33
1

You can't subtract objects, that's why you get the error.

You could use NSDecimalNumber instead of NSNumber and then you have API for decimalNumberBySubtracting:.

Alternatively, use double.

The main point is to use a data type which allows for the level of precision that you're interested in, and that usually relates to the number of and type of calculations you're going to make.

NSNumberFormatter does offer generatesDecimalNumbers (it used to have a bug, not sure if it still does, worth investigation).

Wain
  • 118,658
  • 15
  • 128
  • 151
  • 'You can't subtract objects, that's why you get the error.' brain fart moment. Thanks ill check it out – DevC May 15 '15 at 13:09