I have a char in c#:
char foo = \'2\';
Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value o
I am agree with @Chad Grant
Also right if you convert to string then you can use that value as numeric as said in the question
int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
I tried to create a more simple and understandable example
char v = '1';
int vv = (int)char.GetNumericValue(v);
char.GetNumericValue(v) returns as double and converts to (int)
More Advenced usage as an array
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
Try This
char x = '9'; // '9' = ASCII 57
int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9
I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.
For ex:-
int s;
char i= '2';
s = (int) i;
By default you use UNICODE so I suggest using faulty's method
int bar = int.Parse(foo.ToString());
Even though the numeric values under are the same for digits and basic Latin chars.
This will convert it to an int:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.
This converts to an integer and handles unicode
CharUnicodeInfo.GetDecimalDigitValue('2')
You can read more here.