Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDecimalNumber multiplication strangeness

ExclusivePrice, quantity are both NSDecimalNumbers.

NSDecimalNumber *price = [exclusivePrice decimalNumberByMultiplyingBy:quantity];
NSLog(@"%@ * %@ = %@", exclusivePrice, quantity, price);

The result I get:

2010-04-05 00:22:29.111 TestApp[13269:207] 65 * 2 = -0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007169919476068871316457914368

What I expected:

2010-04-05 00:22:29.111 TestApp[13269:207] 65 * 2 = 130

Can anyone explain this please?

Edit:

Full repro:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSDecimalNumber *n2 = (NSDecimalNumber *)[formatter numberFromString:@"2"];
NSDecimalNumber *n1 = (NSDecimalNumber *)[NSDecimalNumber numberWithInt:65];
NSDecimalNumber *n3 = [n1 decimalNumberByMultiplyingBy:n2];
NSLog(@"%@ * %@ = %@", n1, n2, n3);
like image 462
rein Avatar asked Dec 29 '22 21:12

rein


2 Answers

Seems to work for me.

NSDecimalNumber * n1 = [NSDecimalNumber decimalNumberWithString:@"65"];
NSDecimalNumber * n2 = [NSDecimalNumber decimalNumberWithString:@"2"];

NSDecimalNumber * res = [n1 decimalNumberByMultiplyingBy:n2];

NSLog(@"%@ * %@ = %@", n1, n2, res);

Output:

2010-04-05 08:40:42.812 x[24301] 65 * 2 = 130
like image 98
stefanB Avatar answered Jan 15 '23 02:01

stefanB


I found the answer: According to How to use NSDecimalNumber? I can't easily convert between NSNumber and NSDecimalNumber. To convert from the one to the other I have to do :

NSDecimalNumber *n2 = [NSDecimalNumber decimalNumberWithDecimal:
                              [[formatter numberFromString:@"2"] decimalValue]];

It would have been nice if the NSNumberFormatter had a decimalNumberFromString: method.

like image 22
rein Avatar answered Jan 15 '23 01:01

rein