Converting currency string into NSDecimalNumber

。_饼干妹妹 提交于 2020-01-05 04:37:05

问题


I'm trying to convert some currency string (e.g., $25,000) into NSDecimalNumber using the following code:

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyFormatter setGeneratesDecimalNumbers:TRUE];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

// textField.text is some currency string (e.g., $25,000)
NSDecimalNumber *decimalNumber = [currencyFormatter numberFromString:textField.text];

The compiler is complaining about the resulting type of currencyFormatter, is NSNumber instead of NSDecimalNumber but I'm setting this here:

[currencyFormatter setGeneratesDecimalNumber:TRUE];

So I'm lost. Any ideas?


回答1:


NSDecimalNumber is a subclass of NSNumber. The numberFromString: method of NSNumberFormatter is declared to return NSNumber*, so you need to add a cast:

NSDecimalNumber *decimalNumber = (NSDecimalNumber*)[currencyFormatter numberFromString:textField.text];

Since you have set the behavior to produce decimal numbers, this will work correctly.



来源:https://stackoverflow.com/questions/19551568/converting-currency-string-into-nsdecimalnumber

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