NSNumber arithmetic

Magic Bullet Dave picture Magic Bullet Dave · Jul 8, 2012 · Viewed 7.5k times · Source

I want to perform some simple arithmetic on NSNumbers and preserve the type. Is this possible?

For example:

- (NSNumber *)add:(NSNumber *)firstNumber to:(NSNumber *)secondNumber;

Is my method definition, and firstNumber and secondNumber are integers then I would like to return an integer that is the integer addition of them both. Equally if both are doubles then to return the result as a double.

It looks like I can get the type (except for boolean) using [NSNumber objCType] as found in this question: get type of NSNumber but I can't seem to extract those types and do the calculation without lots of code to extract the values do the calculation and return the result for every possible type.

Is there a short and concise way of doing this?

Answer

aleroot picture aleroot · Jul 8, 2012

If you want to perform arithmetic the best bet would be using an NSDecimalNumber.

NSDecimalNumber have methods to perform arithmetic operations like :

– decimalNumberByAdding:
– decimalNumberBySubtracting:
– decimalNumberByMultiplyingBy:
– decimalNumberByDividingBy:
– decimalNumberByRaisingToPower:
– decimalNumberByMultiplyingByPowerOf10:
– decimalNumberByAdding:withBehavior:
– decimalNumberBySubtracting:withBehavior:
– decimalNumberByMultiplyingBy:withBehavior:
– decimalNumberByDividingBy:withBehavior:
– decimalNumberByRaisingToPower:withBehavior:
– decimalNumberByMultiplyingByPowerOf10:withBehavior:

And since NSDecimalNumber extends NSNumber it also have all methods of an NSNumber, so i think that you could use it in your case without any problem.