使用货币将字符串转换为Double

时间:2012-10-16 17:34:54

标签: ios currency nsnumberformatter

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter   setNumberStyle: NSNumberFormatterCurrencyStyle];
    double value = [[numberFormatter  numberFromString: ProviderTripRate.text] doubleValue];
    [User setDouble:value forKey:@"Trip_Rate"];
NSLog(@"     %@                  %f     " , ProviderTripRate.text  ,   value  );

如果ProviderTripRate.text中的数据是2.75,则值为0错误 如果ProviderTripRate.text中的数据是2.75美元,那么值是2.75正确

如何可靠地从字符串转换为double值 请注意,文本字符串可能有也可能没有本地货币符号($如上所示) 但它应该始终转换

提前致谢

3 个答案:

答案 0 :(得分:1)

试试这个:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSNumber* number = [numberFormatter  numberFromString:ProviderTripRate.text]
if (!number) {
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    number = [numberFormatter  numberFromString:ProviderTripRate.text];
}
double value = [number doubleValue];

答案 1 :(得分:0)

试试这个:

if ([providerTripRate.text hasPrefix:@"$"]) {
    // use NSNumberFormatter to obtain the value
} else {
    float theValue = [providerTripRate.text doubleValue];
}

答案 2 :(得分:0)

extension String {
/// Creates a Double from the string
///
/// Tries various ways of extracting a number, currently handling the following formats
/// - 1000
/// - 1000.00
/// - 1,000.00
/// - $1,000.00
///
/// - Returns: Double value, or 0.0 if a non numerical String is passed
  func asDouble() -> Double {

    if let double = Double(self) {
        return double
    }

    let formatter = NumberFormatter()
    if let number = formatter.number(from: self) {
        return number.doubleValue
    }

    formatter.numberStyle = .currency
    if let number = formatter.number(from: self) {
        return number.doubleValue
    }

    formatter.currencySymbol = ""
    formatter.internationalCurrencySymbol = ""

    if let number = formatter.number(from: self) {
        return number.doubleValue
    }

    return 0
  }
}