2

I have a number string that is in Arabic language, I want to convert it to English, I use this:

let arabicPhoneNumber = "٠١٠١٢٣٤٥٦٧٨٩"
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "EN")
if let number = formatter.number(from: arabicPhoneNumber)?.stringValue {
    print(number) //deletes leading zero
}

the problem is it deletes the leading zero and I want to preserve it as this is a phone number. is there a way to convert phone number string from Arabic to English without losing leading zeros ??

Moaz Ahmed
  • 441
  • 2
  • 8
  • I'm not sure if it fixes the issue, but why set the locale to "EN"? – sdasdadas Nov 30 '16 at 16:21
  • Phone numbers are not actually numbers and such a conversion isn't appropriate. Especially if the phone number has any punctuation (as many formatted phone numbers do). I would suggest you iterate the original string looking for digit characters and convert each digit character. – rmaddy Nov 30 '16 at 16:24
  • Perhaps check this post on preserving country codes? http://stackoverflow.com/questions/34544942/ios-convert-phone-number-to-international-format – Kayla Galway Nov 30 '16 at 16:24
  • Hi Martin, I already found your answer to be beneficial but at that time I didn't have enough reputation to comment or vote up. Thanks – Moaz Ahmed Jul 24 '17 at 11:21

2 Answers2

1

Instead of converting the string to a number, you can do a "transliteration" to the Latin script, using CFStringTransform() from the Foundation library:

let arabicPhoneNumber = "٠١٠١٢٣٤٥٦٧٨٩"

// We need a CFMutableString and a CFRange:
let cfstr = NSMutableString(string: arabicPhoneNumber) as CFMutableString
var range = CFRange(location: 0, length: CFStringGetLength(cfstr))

// Do the transliteration (this mutates `cfstr`):
CFStringTransform(cfstr, &range, kCFStringTransformToLatin, false)

// Convert result back to a Swift string:
let phoneNumber = cfstr as String

print(phoneNumber) // 010123456789

This preserves all digits as well as possible separators.

Remark: The above example (from the question) contains "Arabic Indic" digits, for example ١ = U+0661 = "ARABIC-INDIC DIGIT ONE". These are correctly transliterated on macOS 10.12 and iOS 10.

On earlier OS versions,

CFStringTransform(cfstr, &range, kCFStringTransformLatinArabic, true)
CFStringTransform(cfstr, &range, kCFStringTransformStripCombiningMarks, false)

worked correctly in my tests to convert arabic digits to latin.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

swift 4.0

 func convertToEnDigits(_ digits: String) -> String {
    // We need a CFMutableString and a CFRange:
    let cfstr = NSMutableString(string: digits) as CFMutableString
    var range = CFRange(location: 0, length: CFStringGetLength(cfstr))
    // Do the transliteration (this mutates `cfstr`):
    CFStringTransform(cfstr, &range, kCFStringTransformToLatin, false)
    // Convert result back to a Swift string:
    return (cfstr as String)
}
Kassem Itani
  • 1,057
  • 10
  • 15