Swift iOS - 将货币格式的字符串转换为数字

Swift iOS - Convert currency formatted string to number

我已经使用 NumberFormatter class 将数字转换为货币格式的字符串(例如 2000 -> £2,000.00)。但是我需要一种将格式化字符串转换回数字的方法(例如 £2,000.00 -> 2000)。

事实证明 运行 它通过格式化程序返回是行不通的,只会生成 nil。有谁知道实现此目标的最佳方法?

快速技巧:

let numString = String(number.characters.filter { "0123456789.".characters.contains([=10=]) })           
let number = Double(numString)

Swift 4:以下字符串扩展有助于将货币格式的字符串转换为十进制或双精度。该方法自动识别大多数常用货币的数字格式。

字符串必须没有货币符号(€、$、£、...):

For Example:

US formatted string: "11.233.39" -> 11233.39

European formatted string: "11.233,39" -> 11233.39

// String+DecimalOrDouble

extension String {   
    func toDecimalWithAutoLocale() -> Decimal? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal

        //** US,CAD,GBP formatted
        formatter.locale = Locale(identifier: "en_US")

        if let number = formatter.number(from: self) {
            return number.decimalValue
        }
        
        //** EUR formatted
        formatter.locale = Locale(identifier: "de_DE")

        if let number = formatter.number(from: self) {
           return number.decimalValue
        }
        
        return nil
    }
    
    func toDoubleWithAutoLocale() -> Double? {
        guard let decimal = self.toDecimalWithAutoLocale() else {
            return nil
        }

        return NSDecimalNumber(decimal:decimal).doubleValue
    }
}

在 Playground 中测试的示例:

import Foundation

//US formatted without decimal mark
str = "11233.3"
decimal = str.toDecimalWithAutoLocale() //11233.3
double = str.toDoubleWithAutoLocale() //11233.3

//EU formatted without decimal mark
str = "11233,3"
decimal = str.toDecimalWithAutoLocale() //11233.3
double = str.toDoubleWithAutoLocale() //11233.3

//US formatted with decimal mark
str = "11,233.3"
decimal = str.toDecimalWithAutoLocale() //11233.3
double = str.toDoubleWithAutoLocale() //11233.3

//EU formatted with decimal mark
str = "11.233,3"
decimal = str.toDecimalWithAutoLocale() //11233.3
double = str.toDoubleWithAutoLocale() //11233.3