Terry B
Terry B

Reputation: 221

How do I add NSDecimalNumbers?

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!

Upvotes: 22

Views: 11194

Answers (5)

Integer Poet
Integer Poet

Reputation: 747

NSDecimalNumber is an Objective C class which, when instantiated, produces an object which contains a number. You access the object (and objects in general) through methods only. Objective C doesn't have a way to directly express arithmetic against objects, so you need to make one of three calls:

  • -[NSDecimalNumber doubleValue], which extracts the numbers from your objects before adding the numbers. link
  • -[NSDecimalNumber decimalNumberByAdding], which creates an additional object, which may be more than you want. link
  • NSDecimalAdd, which, again, creates an additional object, which may be more than you want. link

Upvotes: 10

Frank Krueger
Frank Krueger

Reputation: 70983

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++!

Upvotes: 22

Frank Schmitt
Frank Schmitt

Reputation: 25765

You can:

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

The problem with your example is that what self.numOne really is at a bit level is a pointer to an object. So your function would return some random memory location, not the sum.

If Objective-C supported C++-style operator overloading, someone could define + when applied to two NSDecimalNumber objects as an alias to decimalNumberByAdding:. But it doesn't.

Upvotes: 2

Vladimir
Vladimir

Reputation: 170829

See NSDecimalAdd function (as well as NSDecimalMultiply, NSDecimalDivide, NSDecimalSubtract).

Upvotes: 6

newacct
newacct

Reputation: 122429

[[numOne decimalNumberByAdding:numTwo] decimalNumberByAdding:numThree]

Upvotes: 2

Related Questions