Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Arabic String to english number in Swift

Tags:

ios

swift

How to convert non English number to English number like : "٣٤٨٦٩١٢٨٨١" to "3486912881" in Swift or I want to accept just english numbers and obtain others.

In Java Android this code is working 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);
}
like image 555
Mohammad Khir Alsaid Avatar asked Aug 12 '16 18:08

Mohammad Khir Alsaid


3 Answers

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
    }
}
like image 78
Anbu.Karthik Avatar answered Oct 07 '22 22:10

Anbu.Karthik


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"
like image 19
Hossam Ghareeb Avatar answered Oct 07 '22 20:10

Hossam Ghareeb


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: "١٢"))
like image 5
Haitham Alsheikh Avatar answered Oct 07 '22 20:10

Haitham Alsheikh