Abdelrahman Tareq
Abdelrahman Tareq

Reputation: 2317

Convert arabic number to english number & the reverse in Dart

I want to replace Arabic number with English number.

1-2-3-4-5-6-7-8-9 <== ١-٢-٣-٤-٥-٦-٧-٨-٩

Upvotes: 0

Views: 2078

Answers (2)

Anas Esh
Anas Esh

Reputation: 28

0 for english to arabic

1 for arabic to english

convertDigitsLang("1-2-3-4-5-6-7-8-9",0); =>> ١-٢-٣-٤-٥-٦-٧-٨-٩

 String convertDigitsLang(String input,int mode) {
  List<String> arabicNums = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
  RegExp regex = RegExp([r'[0-9]',r'[٠-٩]'][mode]);
  Set<String> matches =
      Set.from(regex.allMatches(input).map((e) => e.group(0).toString()));
  String replacment(String match)=>mode==1?arabicNums.indexOf(match).toString():arabicNums[int.parse(match)];
  matches.forEach((match)=>input=input.replaceAll(match,replacment(match)));
  return input;
} 



Upvotes: 1

Abdelrahman Tareq
Abdelrahman Tareq

Reputation: 2317

Arabic to English

String replaceArabicNumber(String input) {
    const english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const arabic = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];

    for (int i = 0; i < english.length; i++) {
      input = input.replaceAll(arabic[i], english[i]);
    }
    print("$input");
    return input;
  }

to do the opposite replacing the English numbers with the Arabic ones(English to Arabic)

 String replaceEnglishNumber(String input) {
    const english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const arabic = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];

    for (int i = 0; i < english.length; i++) {
      input = input.replaceAll(english[i], arabic[i]);
    }
    print("$input");
    return input;
  }

Upvotes: 4

Related Questions