将NSString转换为float

时间:2013-05-13 15:11:57

标签: cocoa floating-point nsstring

我从用户输入中得到一个NSString,就像这样:$ 10,000.00

我有一个剥离$ off的方法:

- (NSString*) stripDollarSign : (NSString*) stringToStrip {

    //check to see if the number is already formatted correctly
    NSRange dollarSignCheck = [stringToStrip rangeOfString:@"$"];
    //only strip it if it has the $
    if (dollarSignCheck.location != NSNotFound) {

        NSString* cleanedString = [stringToStrip substringWithRange:NSMakeRange(1, stringToStrip.length-1)];
        return cleanedString;
    }

    return 0;

}

我的回报是10,000.00(仍然是NSString)。

如果我使用清理结果执行此操作:

float value = [inputString floatValue]

我明白了:

10.00

如果我尝试将其转换为NSDecimal,我会得到10

[[NSDecimalNumber alloc] initWithString:inputString];

我需要做什么才能转换这个以便获得10,000.00?

3 个答案:

答案 0 :(得分:2)

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencySymbol:@"$"];
[formatter setCurrencyGroupingSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];

NSNumber *n = [formatter numberFromString:@"$10,000.00"];

OR

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setPositiveFormat:@"$###,###.##"];
[formatter setLenient:YES]; // This will forgive you for missing out the $ symbol

答案 1 :(得分:2)

NSNumberFormatter最初似乎是一个很好的前进方式:

  NSString *currencyAmount = @"$10,000.00";
  NSLocale *englishLocale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"];
  NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
  currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
  currencyFormatter.locale = englishLocale;
  NSNumber *number = [currencyFormatter numberFromString: currencyAmount];
  NSLog(@"Got amount: %@", number);

请注意,您可能需要首先在格式化程序上手动设置区域设置 - 当我在我的位置进行测试时,它根本无法处理井号。

答案 2 :(得分:0)

您可以使用NSString方法stringByReplacingOccurrencesOfString:withString:删除逗号。 E.g:

NSString *stringWithoutComma = [cleanedString stringByReplacingOccurrencesOfString:@"," withString:@""];