本文介绍了NSDecimalNumber乘法奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ExclusivePrice,quantity都是NSDecimalNumbers。

ExclusivePrice, quantity are both 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

任何人都可以解释这个问题吗?

Can anyone explain this please?

编辑:

完整再现:

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);


推荐答案

我发现答案:根据如何使用NSDecimalNumber?我不能轻易地在NSNumber和NSDecimalNumber之间转换。要从一个转换到另一个,我必须做:

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]];

如果NSNumberFormatter有一个decimalNumberFromString:方法,将会很好。

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

这篇关于NSDecimalNumber乘法奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!