The int
type (and any other numeric types) just stores values and doesn't care/know whatever format the original string is in. String representation is the thing that only affects input and output
C# supports locales for internationalization through System.Globalization.CultureInfo
and you just need to specify the correct culture (Persian in this case) so that printing and parsing work correctly. In CultureInfo
there's NumberFormatInfo.NativeDigits
that stores the native digits of that locale. If you set NumberFormatInfo.DigitSubstitution
correctly the output will be printed using the correct digit system. Unfortunately while that works for formatted output, Int.Parse
doesn't use that information to parse numbers in native digits so you have to translate the digits yourself. Here's a solution that works for any cultures
using System;
using System.Globalization;
public class Program
{
public static string GetWesternRepresentation(string input, CultureInfo cultureInfo)
{
var nativeDigits = cultureInfo.NumberFormat.NativeDigits;
return input.Replace(cultureInfo.NumberFormat.NumberDecimalSeparator, ".")
.Replace(cultureInfo.NumberFormat.NumberGroupSeparator, ",")
.Replace(cultureInfo.NumberFormat.NegativeSign, "-")
.Replace(cultureInfo.NumberFormat.PositiveSign, "+")
.Replace(nativeDigits[0], "0")
.Replace(nativeDigits[1], "1")
.Replace(nativeDigits[2], "2")
.Replace(nativeDigits[3], "3")
.Replace(nativeDigits[4], "4")
.Replace(nativeDigits[5], "5")
.Replace(nativeDigits[6], "6")
.Replace(nativeDigits[7], "7")
.Replace(nativeDigits[8], "8")
.Replace(nativeDigits[9], "9");
}
public static void Main()
{
try
{
var culture = new CultureInfo("fa"); // or fa-Ir for Iranian Persian
string input = "۱۲۳";
// string input = "١٢٣"; // won't work although looks almost the same
string output = GetWesternRepresentation(input, culture);
Console.WriteLine("{0} -> {1}", input, output);
int number = Int32.Parse(output, CultureInfo.InvariantCulture);
Console.WriteLine("Value: {0}", number);
}
catch (FormatException)
{
Console.WriteLine("Bad Format");
}
catch (OverflowException)
{
Console.WriteLine("Overflow");
}
}
}
You can try this on .NET Fiddle
Now you may see that when changing the input to the commented out line it won't work although the strings look almost the same. That's because your digits above above are Eastern Arabic digits (٠١٢٣٤٥٦٧٨٩ - code points U+0660-U+0669) and not Persian digits (۰۱۲۳۴۵۶۷۸۹ - code points U+06F0-U+06F9)