Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert first symbol of string to int, getting weird value

Tags:

string

c#

integer

static void Main(string[] args)
{
    string str_val = "8584348,894";
    //int prefix = Convert.ToInt32(str_val[0]); //prefix = 56 O_o
    //int prefix = (int)str_val[0]; //what, again 56? i need 8!
    int prefix = Convert.ToInt32("8"); //at least this works -_-
}

Any idea how to convert first symbol to right numeric value?

like image 828
Kosmo零 Avatar asked Nov 30 '25 05:11

Kosmo零


2 Answers

If you use:

Convert.ToInt32(str_val[0]);

then you are actually calling the overload:

Convert.ToInt32(char val);

which gives the Unicode/Ascii number of character being passed as a parameter.

If you want to convert first character, you need to force it to be a string type:

Convert.ToInt32(str_val.Substring(0, 1));

This way you call the overload:

Convert.ToInt32(string val);

which actually do what you want (convert string value to int value that this string represents).

like image 102
Kuba Wyrostek Avatar answered Dec 02 '25 19:12

Kuba Wyrostek


Your trying to parse a string but passing in a char. Convert the character to a string first.

int prefix = Convert.ToInt32(str_val[0].ToString());

So the character value of 8 is the ASCII value 56, what you want to do is inteprete the value as a string rather than an ASCII Value. By using the .ToString() method you are converting the character into a null terminated string, which can be read by the ToInt32 method.

like image 38
John Mitchell Avatar answered Dec 02 '25 17:12

John Mitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!