【问题标题】:iPhone: How do I convert a string with a currency symbol to a negative number?iPhone:如何将带有货币符号的字符串转换为负数?
【发布时间】:2010-09-27 12:02:38
【问题描述】:

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

我有这部分

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

【问题讨论】:

    标签: iphone xcode iphone-sdk-3.0


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用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]);
      

      【讨论】:

      • 我收到一个警告...警告:“NSDecimalNumber”可能无法响应“-descriptionWithLocale”还有一个错误 -[NSDecimalNumber descriptionWithLocale]:无法识别的选择器发送到实例 0x595cde0 ***由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSDecimalNumber descriptionWithLocale]:无法识别的选择器发送到实例 0x595cde0”在抛出“NSException”实例后终止调用
      • 对此感到抱歉。最后一条语句更新为仅使用 description
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多