How do I add NSDecimalNumbers?

Terry B picture Terry B · Mar 15, 2010 · Viewed 10.6k times · Source

OK this may be the dumb question of the day, but supposing I have a class with :

NSDecimalNumber *numOne   = [NSDecimalNumber numberWithFloat:1.0];
NSDecimalNumber *numTwo   = [NSDecimalNumber numberWithFloat:2.0];
NSDecimalNumber *numThree = [NSDecimalNumber numberWithFloat:3.0];

Why can't I have a function that adds those numbers:

- (NSDecimalNumber *)addThem {
    return (self.numOne + self.numTwo + self.numThree);
}

I apologize in advance for being an idiot, and thanks!

Answer

Frank Krueger picture Frank Krueger · Mar 15, 2010

You can't do what you want becuase neither C nor Objective C have operator overloading. Instead you have to write:

- (NSDecimalNumber *)addThem {
    return [self.numOne decimalNumberByAdding:
        [self.numTwo decimalNumberByAdding:self.numThree]];
}

If you're willing to play dirty with Objective-C++ (rename your source to .mm), then you could write:

NSDecimalNumber *operator + (NSDecimalNumber *a, NSDecimalNumber *b) {
    return [a decimalNumberByAdding:b];
}

Now you can write:

- (NSDecimalNumber *)addThem {
    return self.numOne + self.numTwo + self.numThree;
}

Go C++!