I have a string containing a number in a non-ascii format e.g. unicode BENGALI DIGIT ONE (U+09E7) : \"১\"
How do I parse this as an integer in .NET?
You could create a new string that is the same as the old string except the native digits are replaced with Latin decimal digits. This could be done reliably by looping through the characters and checking the value of char.IsDigit(char)
. If this function returns true, then convert it with char.GetNumericValue(char).ToString()
.
Like this:
static class DigitHelper
{
public static string ConvertNativeDigits(this string text)
{
if (text == null)
return null;
if (text.Length == 0)
return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (char character in text)
{
if (char.IsDigit(character))
sb.Append(char.GetNumericValue(character));
else
sb.Append(character);
}
return sb.ToString();
}
}
int value = int.Parse(bengaliNumber.ConvertNativeDigits());