Convert Arabic String to English number in Swift

How to convert a non-English number to an English number, for example: "3486912881" to "3486912881" in Swift or I want to accept only English numbers and get others.

in Java Android, this code works for me:

private static String arabicToDecimal(String number) {
    char[] chars = new char[number.length()];
    for(int i=0;i<number.length();i++) {
        char ch = number.charAt(i);
        if (ch >= 0x0660 && ch <= 0x0669)
           ch -= 0x0660 - '0';
        else if (ch >= 0x06f0 && ch <= 0x06F9)
           ch -= 0x06f0 - '0';
        chars[i] = ch;
    }
    return new String(chars);
}
+6
source share
4 answers

like

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

output

enter image description here

+14
source

The problem with use NumberFormatteris that it will ignore other non-digital characters, for example if you Hello ١٢٣have one 123. To save other characters and only convert numeric, 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"
+12

Swift 3.0 :

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

, :

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
}

:

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

Source: https://habr.com/ru/post/1651103/


All Articles