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

后端 未结 15 2148
终归单人心
终归单人心 2021-02-02 07:10

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

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

to

string Value=\"1036751\"         


        
15条回答
  •  庸人自扰
    2021-02-02 07:29

    USE Culture To convert the number from any language to any language

    Functions:

    public static string ConvertDigitChar(this string str, CultureInfo source, CultureInfo destination)
    {
        for (int i = 0; i <= 9; i++)
        {
            str = str.Replace(source.NumberFormat.NativeDigits[i], destination.NumberFormat.NativeDigits[i]);
        }
        return str;
    }
    
    public static string ConvertDigitChar(this int digit, CultureInfo destination)
    {
        string res = digit.ToString();
        for (int i = 0; i <= 9; i++)
        {
            res = res.Replace(i.ToString(), destination.NumberFormat.NativeDigits[i]);
        }
        return res;
    }
    

    How to use the functions:

    var fa = CultureInfo.GetCultureInfoByIetfLanguageTag("fa");
    var en = CultureInfo.GetCultureInfoByIetfLanguageTag("en");
    string str = "۰0۱1۲2۳3۴4۵5۶6۷7۸8۹9";
    string r1 = str.ConvertDigitChar(en, fa);
    string r2 = str.ConvertDigitChar(fa, en);
    int i = 123456789;
    string r3 = i.ConvertDigitChar(fa);
    

    Result:

    r1: "۰۰۱۱۲۲۳۳۴۴۵۵۶۶۷۷۸۸۹۹"

    r2: "00112233445566778899"

    r3: "۰۱۲۳۴۵۶۷۸۹"

提交回复
热议问题