How to Convert String to Integer in C#

How can I convert String to Int?

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN

C# Convert String to Integer

You can use Convert.ToInt32() method to convert your String into integer

Try This:

      //lblTemp.Text = "" + Temperature;  this statement is not required.
if (Convert.ToInt32(Temperature) <= 32)
{
lblResult.Text = "It is freezing outside!";
}

OR

you can use int.TryParse() method to perform the proper conversion even if the data is invalid.

Try This:

        int temp;
if (int.TryParse(Temperature,out temp))
{
if(temp <= 32)
lblResult.Text = "It is freezing outside!";
}

Convert string to INT in C# (When String is 'E0305' To convert INT is not Work

If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:

string val = "F0005";
if (int.TryParse(val, out int i) {
// parse success. you can use i here
}
else {
// parse failed.
}

If you really want it to be 0, this should work

string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;

Convert a string to integer in C#/.NET

Use Double.TryParse() and once you get the value from it, convert it to int using Convert.ToInt():

double parsedNum;
if (Double.TryParse(YourString, out parsedNum) {
newInt = Convert.ToInt32(num);
}
else {
newInt = 0;
}

Convert String to Integer

Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.

string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}

How to convert a string to integer?

You could do it like this with simple splitting:

string s = "12:40 PM";
int HRS= Convert.ToInt32(s.Split(':')[0]);
int MINS= Convert.ToInt32(s.Split(':')[1].Split(' ')[0]);

or you use the DateTime.ParseExact() Method like:

string s = "12:40 PM";
DateTime time = DateTime.ParseExact(s,"hh:mm tt",CultureInfo.InvariantCulture);
int HRS = time.Hour;
int MINS= time.Minute;

Convert string[] to int[] in one line of code using LINQ

Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));

Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse);

A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray();

Converting String to Integer without using Multiplication C#

If you assume a base-10 number system and substituting the multiplication by bit shifts (see here) this can be a solution for positive integers.

public int StringToInteger(string value)
{
int number = 0;
foreach (var character in value)
number = (number << 1) + (number << 3) + (character - '0');

return number;
}

See the example on ideone.

The only assumption is that the characters '0' to '9' lie directly next to each other in the character set. The digit-characters are converted to their integer value using character - '0'.

Edit:

For negative integers this version (see here) works.

public static int StringToInteger(string value)
{
bool negative = false;
int i = 0;

if (value[0] == '-')
{
negative = true;
++i;
}

int number = 0;
for (; i < value.Length; ++i)
{
var character = value[i];
number = (number << 1) + (number << 3) + (character - '0');
}

if (negative)
number = -number;
return number;
}

In general you should take errors into account like null checks, problems with other non numeric characters, etc.



Related Topics



Leave a reply



Submit