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);
}
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
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
}
}
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"
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: "١٢"))
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