假设我有一个23.56英镑或23.56美元的字符串,如何将其转换为-23.56?
我有这个部分
NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
[strAmount replaceCharactersInRange: [strAmount rangeOfString: strCurrencySymbol] withString:@""];
答案 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]);