1

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?

Navid_pdp11
  • 3,487
  • 3
  • 37
  • 65
  • 2
    Maybe u should check out this http://stackoverflow.com/questions/5879437/how-to-convert-arabic-number-to-int – Flardryn Mar 04 '17 at 14:18

2 Answers2

1
    Int32 value = 0;
    if (Int32.TryParse(String.Join(String.Empty, "۱۱۷".Select(Char.GetNumericValue)), out value))
    {
        Console.WriteLine(value);
        //....
    }
Sergey Vasiliev
  • 803
  • 8
  • 19
1

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.

Demo

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);
}
aloisdg
  • 22,270
  • 6
  • 85
  • 105