How to perform NSDecimal Math?

98 views Asked by At

I am attempting to perform basic NSDecimal math such as addition multiplication and subtraction of NSDecimals. Is this possible to accomplish? trying to use NSDecimalAdd getting error

NSDecimal' to parameter of incompatible type 'NSDecimal * _Nonnull'

_meat.colonyQueenObject.count.creatureCount = [colonyQueenNumber decimalValue];


-(void)adjustCountsCreatureCountforAddedCreatures:(NSDecimal)creaturesAdded meatCount:(NSDecimal)meatCount larvaCount:(NSDecimal)larvaCount creatureType:    (int)creatureType{

    NSDecimalAdd(_meat.colonyQueenObject.count.creatureCount, _meat.colonyQueenObject.count.creatureCount, &creaturesAdded, NSRoundBankers);


    }


   NSDecimalAdd(&_meat.colonyQueenObject.count.creatureCount, &_meat.colonyObject.count.creatureCount, &creaturesAdded, NSRoundBankers);

also fails

1

There are 1 answers

0
CRD On BEST ANSWER

NSDecimal is a value type; just like int, float, etc. However the math functions, such as NSDecimalAdd, take their arguments and return their result by address - that is the arguments & result must be variables passed by address, obtained using the & operator, to the function and not by value.

Your second attempt:

NSDecimalAdd(&_meat.colonyQueenObject.count.creatureCount,
             &_meat.colonyObject.count.creatureCount,
             &creaturesAdded,
             NSRoundBankers);

is the closest to being correct, but the first two arguments are incorrect as you are attempting to pass the address of a property - which is not possible. So you should be seeing an error like:

Address of a property expression requested

If you wish to use properties you will have to use temporary intermediate local variables to hold your values. E.g. something along the lines of:

NSDecimal leftOperand = _meat.colonyObject.count.creatureCount; // copy left operand value to variable
NSDecimal result; // variable for result
NSDecimalAdd(&result,
             &leftOperand,
             &creaturesAdded,
             NSRoundBankers);
_meat.colonyQueenObject.count.creatureCount = result; // assign result to property

You should also be checking the return value of NSDecimalAdd as it indicates whether the operation was performed correctly (NSCalculationNoError).

HTH