Convert string to int

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have tried several methods in converting my string data to an int. I am
getting a message back 'Input string was not in a correct format'

strSQL1 = "SELECT [service-cost] FROM [task] WHERE [service-order-number] =
" + Convert.ToInt32(txtSON.Text);

cmSQL1 = new SqlCommand(strSQL1,cnKennel);
if (cnKennel.State != ConnectionState.Open)
cnKennel.Open();
drSQL1 = cmSQL1.ExecuteReader();

if(drSQL1.Read())
{
lcost = drSQL1["service-cost"].ToString();
}

cnKennel.Close();

cost1 = int.Parse(lcost);

where cost1 is defined as a int, and lcost is a string. the data in lcost =
"35.00".

How do I fix this problem, I need help??
 
nbohana said:
I have tried several methods in converting my string data to an int. I am
getting a message back 'Input string was not in a correct format'
cost1 = int.Parse(lcost);

where cost1 is defined as a int, and lcost is a string. the data in lcost =
"35.00".

How do I fix this problem, I need help??

"35.00" is not an integer, it's a floating point value. Arguably you
could say it's an integer because the part after the decimal point is
".00", but it's still formatted as a floating point value so Int32.Parse
will definitely not like it.

If you know it's always ".00", you could either:

- remove ".00" by using .Replace(".00", ""), before running it through
Int32.Parse
- use Double.Parse, and Convert.ToInt32 afterwards
 
35.00 is not valid for an int
Parse it to float and then cast to int
Take care to use appropriate CultureInfo too.

int parsed = (int)float.Parse("35.00", yourCultureInfo.NumberFormat);
 
"35.00" is a floating point value so it cannot be parsed to an int. You can
use double.Parse to parse the value to a Double instead of an int. Still,
since you're reading the value from a SqlDataReader, a better option is to
use the GetDouble method of the SqlDataReader.

Anders Norås
http://dotnetjunkies.com/weblog/anoras
 
Just parse it using things like Double.Parse. It you are sure it is an
int, cast to int.
 
Back
Top