Search code examples
iphoneobjective-ciosxcodensdecimalnumber

Multiplying 3 NSDecimalNumber(s) simultaneously


First of all, I'm using NSDecimalNumbers because I'm dealing with currency. I'm not having any trouble with the decimal numbers themselves, I would like to know if it's possible to multiply 3 NSDecimalNumber(s) at the same time.

In other words, if I was multiplying 3 integers I would simply:

int a = 2;
int b = 5;
int c = 7;

int x = a * b * c;

However, in order to multiply NSDecimalNumbers you're forced to use the decimalNumberByMultiplyingBy method.

Using this method, I have to do 2 calculations in order to multiply the 3 NSDecimalNumbers I'm dealing with, like so:

NSDecimalNumber *d1 = [NSDecimalNumber decimalNumberWithString:@"1.502"];
NSDecimalNumber *d2 = [NSDecimalNumber decimalNumberWithString:@"12.472"];
NSDecimalNumber *d3 = [NSDecimalNumber decimalNumberWithString:@"0.765"];

//Calculation
NSDecimalNumber *initialValue = [d1 decimalNumberByMultiplyingBy:d2];
NSDecimalNumber *finalValue = [initialValue decimalNumberByMultiplyingBy:d3];

//Formatting
NSString *output = [NSString stringWithFormat:@"%@", finalValue];
NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:output];

//r is my NSNumberFormatter, which I've configured elsewhere
NSString *s = [r stringFromNumber:n];

NSLog(@"%@",s);

Is there a way to multiply all 3 NSDecimalNumbers at the same time instead of this clunky way around it?


Solution

  • No is the answer. Multiplication is a binary operation. Even

    int x = a * b * c;
    

    actually involves two separate multiplications. It looks less clunky because of the infix notation.

    You can do

    result = [[d1 decimalNumberByMultiplyingBy: d2] decimalNumberByMultiplyingBy: d3];
    

    which is the equivalent to the first statement.