Convert Arabic String to english number in Swift

The problem with using NumberFormatter is that it will ignore other non numeric characters, for example if you have Hello ١٢٣ it will be 123. To keep other characters and only convert numeric ones, you can use the following:

public extension String {

public var replacedArabicDigitsWithEnglish: String {
    var str = self
    let map = ["٠": "0",
               "١": "1",
               "٢": "2",
               "٣": "3",
               "٤": "4",
               "٥": "5",
               "٦": "6",
               "٧": "7",
               "٨": "8",
               "٩": "9"]
    map.forEach { str = str.replacingOccurrences(of: $0, with: $1) }
    return str
}
}

/// usage

"Hello ١٢٣٤٥٦٧٨٩١٠".replacedArabicDigitsWithEnglish // "Hello 12345678910"

do like

     let NumberStr: String = "٢٠١٨-٠٦-٠٤"
    let Formatter = NumberFormatter()
    Formatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
    if let final = Formatter.number(from: NumberStr) {
        print(final)

    }

output

enter image description here

the alternate way

Option 2

extension String {
    public var arToEnDigits : String {
        let arabicNumbers = ["٠": "0","١": "1","٢": "2","٣": "3","٤": "4","٥": "5","٦": "6","٧": "7","٨": "8","٩": "9"]
        var txt = self
        arabicNumbers.map { txt = txt.replacingOccurrences(of: $0, with: $1)}
        return txt
    }
}

To use above codes as function try this:

func toEnglishNumber(number: String) -> NSNumber {

       var result:NSNumber = 0

    let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "EN")
    if let finalText = numberFormatter.number(from: number)
    {
        print("Intial text is: ", number)
        print("Final text is: ", finalText)


        result =  finalText

    }


     return result
}

To use the function:

 print(toEnglishNumber(number: "١٢"))

Tags:

Ios

Swift