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)")
locale = Locale(identifier: "AR") let arabicNumber = numberFormatter. number(from: self) return "\(arabicNumber!)" }
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With