NSDecimalNumber multiplication strangeness

血红的双手。 提交于 2020-01-11 06:01:19

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2576109/nsdecimalnumber-multiplication-strangeness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!