0

Possible Duplicate:
C# char to int

I have come across many solutions to this but I can't get it right by trying any of them. How can I convert string values like "230", "73400" or bigger to int values in c#? Will I have to use a library? Is there a way to do it natively to c#? Lets assume:

string c = "270"; int i;

How can I get i to be 270 as well?

Community
  • 1
  • 1
Snebhu
  • 1,077
  • 1
  • 12
  • 19
  • Are you asking about converting a string containing the characters '2', '7' and '0' to an int? – Andrew Kennan Dec 03 '12 at 06:51
  • Ok, I realised I should have mentioned an array of characters or a string. I was having difficulty with some parsing methods, but methods like sscanf and atoi worked great for me! thanks everyone :) – Snebhu Dec 03 '12 at 07:13

4 Answers4

2

This doesn't seem to be possible char c = '270';

but you can have a string string c ="270"; and the best way would be to go by using int.TryParse(c, out intval) variant which would return true if you have a parsable int value contained in the string. Also in the value examples you mentioned i think you would need a long.

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
1

try this one,

int i = (int) c;
John Woo
  • 258,903
  • 69
  • 498
  • 492
0
int i = Char.GetNumericValue('270');

//or 

int i= Convert.ToInt32(c);

try this,

Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
0

If you have a string containing "270" you can use a few different methods:

var s = "270";

var i1 = Convert.ToInt32(s);
var i2 = int.Parse(s);

// This is probably safest as it allows you to handle errors yourself without catching exceptions.
int i3;
if(! int.TryParse(s, out i3)) {
  // Panic!
}
Andrew Kennan
  • 13,947
  • 3
  • 24
  • 33