iPhone:如何将带有货币符号的字符串转换为负数?

时间:2010-09-27 12:02:39

标签: iphone xcode iphone-sdk-3.0

假设我有一个23.56英镑或23.56美元的字符串,如何将其转换为-23.56?

我有这个部分

NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
[strAmount replaceCharactersInRange: [strAmount rangeOfString: strCurrencySymbol]  withString:@""];

2 个答案:

答案 0 :(得分:0)

这看起来是一个好的开始。在创建一组货币符号后,您可以使用rangeOfCharacterFromSet:代替rangeOfString:。您的代码可能如下所示:

NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
NSCharacterSet *currencySet = [NSCharacterSet characterSetWithCharactersInString:@"$€£"];
[strAmount replaceCharactersInRange: [strAmount rangeOfCharacterFromSet:currencySet]  withString:@"-"];

答案 1 :(得分:0)

使用NSNumberFormatter

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLenient:YES];

NSNumber *number = [formatter numberFromString:@"£23.56"];

NSDecimalNumber *minusOne = [NSDecimalNumber decimalNumberWithString:@"-1.00"];
NSDecimalNumber *money = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];
NSDecimalNumber *negativeMoney = [money decimalNumberByMultiplyingBy:minusOne];

NSLog(@"£23.56 is now %@", [negativeMoney description]);