NSDecimalNumber multiplication strangeness
ExclusivePrice, quantity are both NSDecimalNumbers.
NSDecimalNumber *price = [exclusi开发者_StackOverflow社区vePrice 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);
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
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.
精彩评论