Massey
Massey

Reputation: 1125

How to convert string to int in C#

Sorry, I am new to C#. I am getting a value for quantity from sqlserver. Usually, it comes as a decimal string. For example as "6.00". I have to store it as an int in a C# variable. I am doing the following which worked in a few rows of data I have tested:

int newVal = 
    Convert.ToInt32(Convert.ToDecimal(drUsers["quantity"].ToString()));

If I convert directly to int without converting it first to decimal then it throws "Input not in correct format" error. Is there a better way of doing it, especially to handle data errors such as null coming from the database.

Thanks

Upvotes: 0

Views: 3729

Answers (2)

Dortimer
Dortimer

Reputation: 617

If you know for sure that the value you're getting is going to be a decimal you could just use

int newVal = (int)Decimal.Parse(drUsers["quantity"]);

If you want to be safe and program defensively, I'd suggest using Decimal.TryParse() something along the lines of:

decimal foo = 0;
int newVal = 0;

if(Decimal.TryParse(drUsers["quantity"], out foo) {
    newVal = (int)foo;
} else {
    //handle error
}

EDIT: switched double to decimal, but I think the choice depends on the accuracy you need with the decimal. Database types don’t always match 1:1 with types in c# so either should be okay.

Upvotes: 1

hardkoded
hardkoded

Reputation: 21695

I would avoid the ToSring(). You can get the quantity as a decimal using the Field method.

Convert.ToInt32(drUsers.Field<decimal>("quantity"));

Upvotes: 1

Related Questions