Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Persian Digits in variable to English Digits Using Culture?

I want to change persian numbers which are saved in variable like this :

string Value="۱۰۳۶۷۵۱";  

to

string Value="1036751"; 

How can I use easy way like culture info to do this please?

my sample code is:

List<string> NERKHCOlist = new List<string>(); NERKHCOlist = ScrappingFunction(NERKHCO, NERKHCOlist); int NERKHCO_Price = int.Parse(NERKHCOlist[0]);//NERKHCOlist[0]=۱۰۳۶۷۵۱  

<= So it can not Parsed it to int
And This is in my function which retun a list with persian digits inside list items

protected List<string> ScrappingFunction(string SiteAddress, List<string> NodesList) {         string Price = "null";     List<string> Targets = new List<string>();     foreach (var path in NodesList)     {         HtmlNode node = document.DocumentNode.SelectSingleNode(path.ToString());//recognizing Target Node         Price = node.InnerHtml;//put text of target node in variable(PERSIAN DIGITS)         Targets.Add(Price);     }     return Targets; } 
like image 963
Amin AmiriDarban Avatar asked Aug 20 '13 16:08

Amin AmiriDarban


2 Answers

Simply Use the code below :

private string changePersianNumbersToEnglish(string input) {   string[] persian = new string[10] { "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹" };     for (int j=0; j<persian.Length; j++)       input = input.Replace(persian[j], j.ToString());     return input;  } 
like image 195
Shadmehr Vadoodi Avatar answered Oct 11 '22 08:10

Shadmehr Vadoodi


I suggest two approaches to handle this issue(I Create an extension method for each of them):

1.foreach and replace

public static class MyExtensions {      public static string PersianToEnglish(this string persianStr)      {             Dictionary<char, char> LettersDictionary = new Dictionary<char, char>             {                 ['۰'] = '0',['۱'] = '1',['۲'] = '2',['۳'] = '3',['۴'] = '4',['۵'] = '5',['۶'] = '6',['۷'] = '7',['۸'] = '8',['۹'] = '9'             };             foreach (var item in persianStr)             {                 persianStr = persianStr.Replace(item, LettersDictionary[item]);             }             return persianStr;      } } 

2.Dictionary.Aggregate

public static class MyExtensions {       public static string PersianToEnglish(this string persianStr)       {             Dictionary<string, string> LettersDictionary = new Dictionary<string, string>             {                 ["۰"] = "0",["۱"] = "1",["۲"] = "2",["۳"] = "3",["۴"] = "4",["۵"] = "5",["۶"] = "6",["۷"] = "7",["۸"] = "8",["۹"] = "9"             };             return LettersDictionary.Aggregate(persianStr, (current, item) =>                          current.Replace(item.Key, item.Value));       } } 

More info about Dictionary.Aggregate: Microsoft

Usage:

string result = "۱۰۳۶۷۵۱".PersianToEnglish(); 
like image 41
Iman Bahrampour Avatar answered Oct 11 '22 08:10

Iman Bahrampour