ExclusivePrice,數量都是NSDecimalNumbers。NSDecimalNumber乘法奇怪
NSDecimalNumber *price = [exclusivePrice decimalNumberByMultiplyingBy:quantity];
NSLog(@"%@ * %@ = %@", exclusivePrice, quantity, price);
結果我得到:
2010-04-05 00:22:29.111 TestApp[13269:207] 65 * 2 = -0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007169919476068871316457914368
我期待什麼:
2010-04-05 00:22:29.111 TestApp[13269:207] 65 * 2 = 130
任何人能解釋這個嗎?
編輯:
全部攝製:
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);
我只是看着它。看來NSNumber用於格式化和簡單比較,而在使用十進制數的算術運算中使用NSDecimalNumber。所以雖然你可以從字符串創建NSDecimalNumber,但是你不能從double或float創建它,但你可以從int或float創建NSNumber ... – stefanB 2010-04-04 23:29:40