Iphone – provide to NSDecimalAdd() the same NSDecimal used as leftOperand also as result

cocoa-touchiphoneuikit

I am not sure if that would make any trouble. Normally, lets say, I sum up a few values. I would do it like this:

val1 = val1 + val2;
val1 = val1 + val3;
val1 = val1 + val4;

and so on…
Could I do something similar with NSDecimal, or should I not provide the same NSDecimal "object" twice in the parameters? (btw, how's that called? not a "object", right?)

Apple says:

NSDecimalAdd
Adds two decimal values.

NSCalculationError NSDecimalAdd (
   NSDecimal *result,
   const NSDecimal *leftOperand,
   const NSDecimal *rightOperand,
   NSRoundingMode roundingMode
);

Discussion Adds leftOperand to
rightOperand and stores the sum in
result.

Best Answer

The following code will do the addition you describe above:

NSCalculationError calculationError = NSDecimalAdd(&val1, &val1, &val2, NSRoundBankers);
calculationError = NSDecimalAdd(&val1, &val1, &val3, NSRoundBankers);
calculationError = NSDecimalAdd(&val1, &val1, &val4, NSRoundBankers);

assuming that you've set up val1, val2, and val3 as NSDecimals. In this case, I'm using the Banker's rounding behavior in the case of an overflow.

We use NSDecimal at the heart of the Core Plot framework, so we've created some helper functions that make doing this kind of math a little easier (if a little less efficient, due to the copying of structs during every function call). These can be found in the CPUtilities.m source file within the project.