Reputation: 4012
I have a string from a source which is a unicode digital number like this:
n = ۱۱۷ => 117
now I want to convert this string to int. but when i try to use Convert.ToInt I get this exception. How can I resolve this problem?
Upvotes: 2
Views: 3976
Reputation: 23521
We will use the method GetNumericValue()
, to convert each character into a number. The documentation is clear:
Converts a specified numeric Unicode character to a double-precision floating-point number.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine(ParseNumeric("۱۱۷"));
}
public static int ParseNumeric(string input)
{
return int.Parse(string.Concat(input.Select(c =>
"+-".Contains(c)
? c.ToString()
: char.GetNumericValue(c).ToString())));
}
}
And if you want to support double
, replace int
with double
and add a .
in the string before Contains()
.
If you prefer to use TryParse
instead of a basic Parse
here you go:
public static bool TryParseNumeric(string input, out int numeric)
{
return int.TryParse(string.Concat(input.Select(c =>
"+-".Contains(c)
? c.ToString()
: char.GetNumericValue(c).ToString())), out numeric);
}
Upvotes: 2
Reputation: 823
Int32 value = 0;
if (Int32.TryParse(String.Join(String.Empty, "۱۱۷".Select(Char.GetNumericValue)), out value))
{
Console.WriteLine(value);
//....
}
Upvotes: 3