Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert Arabic numbers to English numbers in swift?

in my app, I have 5 uitextfields. My intended users are Arabic speakers so when they use my app, they will either insert number in English or in Arabic.

The app works just fine with English numbers. However, when I run it and insert numbers in Arabic, the app deals with the textfields as if they all were empty and gives the answer as 0

How can I make sure that the textfields are not nill AND a double, whithout ignoring Arabic numbers?

This is the code inside the "calButton" function:

     /*let value1 = Double(income.text ?? "") ?? 0
    let value2 = Double(salaries.text ?? "") ?? 0
    let value3 = Double(tools.text ?? "") ?? 0
    let value4 = Double(maintinance.text ?? "") ?? 0
    let value5 = Double(otherExpenses.text ?? "") ?? 0
    let sum = value1 - ( value2 + value3 + value4 + value5)

    print("result is: \(sum)")*/



    let textFields = [income, salaries, tools, maintinance, otherExpenses]
    var sum = 0.0
    for textField in textFields {
        if let number = Double((textField?.text!)!) { //checks that it is not nil AND a Double
            sum += number
        }
    }

    expensesTotal.text = String(sum)
    // print("result is: \(sum)")
like image 761
user2066392 Avatar asked Jan 16 '17 01:01

user2066392


People also ask

How can I convert Arabic number to English in Swift?

locale = Locale(identifier: "AR") let arabicNumber = numberFormatter. number(from: self) return "\(arabicNumber!)" }


1 Answers

You need to convert the arabic number string to english first and then do the calculation part.

    let numberStr: String = "٨٦٩١٢٨٨١"
    let formatter: NumberFormatter = NumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
    let final = formatter.number(from: numberStr)
    let doubleNumber = Double(final!)
    print("\(doubleNumber)")
like image 91
Jen Jose Avatar answered Sep 19 '22 13:09

Jen Jose