问题
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