0

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

2
  • If it's already a number in the database, you might just be able to cast it. Have you tried that? Commented Mar 13, 2019 at 18:39
  • 1
    TryParse will return false if the conversion fails, which will allow you to handle invalid data without throwing an exception. Commented Mar 13, 2019 at 18:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If it's already a Decimal, wouldn't it be safer to use Decimal.Parse?
It depends on what the data looks like from the database. If it's a short decimal like "4.243" then Double will suffice, but if it's something "extreme" like "4.2342353252234232423435143621345435343234234" you'll probably want to use Decimal.Parse for higher accuracy. net-informations.com/q/faq/float.html here's a little more information on the differences.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.