Skip to content

Instantly share code, notes, and snippets.

@abspr
Last active January 15, 2023 10:04
Show Gist options
  • Save abspr/a574d4085ab7b505e2957b147f2af287 to your computer and use it in GitHub Desktop.
Save abspr/a574d4085ab7b505e2957b147f2af287 to your computer and use it in GitHub Desktop.
String extension for converting Persian/Arabic numbers to english numbers. It's very useful when your giving a number from user in UITextfield and user enters the numbers with Persian/Arabic Keypad. Usage: "۰۹۴۳۲۴".englishNumbers()
extension String {
func englishNumbers() -> String? {
let oldCount = self.characters.count
let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "EN")
if let final = formatter.number(from: self) {
let newCount = "\(final)".characters.count
let differ = oldCount - newCount
if differ == 0 {
return "\(final)"
} else {
var outFinal = "\(final)"
for _ in 1...differ {
outFinal = "0" + outFinal
}
return outFinal
}
} else {
return nil
}
}
}
@alhoqbani
Copy link

Why not textField.text?.applyingTransform(StringTransform.toLatin, reverse: false) ?

https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform

@mehdico
Copy link

mehdico commented Dec 11, 2018

Why not textField.text?.applyingTransform(StringTransform.toLatin, reverse: false) ?

https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform

not working.

@MehdiAbdi
Copy link

Why not textField.text?.applyingTransform(StringTransform.toLatin, reverse: false) ?
https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform

not working.

This will work but you need to use latinToArabic Like This -> .applyingTransform(StringTransform.latinToArabic, reverse: false)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment