NSDecimalNumber 乘法奇怪
ExclusivePrice、数量都是 NSDecimalNumbers。
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎对我有用。
输出:
Seems to work for me.
Output:
我找到了答案:根据 How to use NSDecimalNumber? 我无法轻松在 NSNumber 和 NSDecimalNumber 之间转换。要从一种转换为另一种,我必须这样做:
如果 NSNumberFormatter 有一个decimalNumberFromString: 方法,那就太好了。
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 :
It would have been nice if the NSNumberFormatter had a decimalNumberFromString: method.