How do I cast a double to an int?

10,295

Solution 1

You say you want an int cast, but you actually need to cast to a double. You can do that like so (Example Code):

Refurb_Rate = (double)totalRefurb / (double)totalUnits * 100d;

Otherwise, you need to change Refurb_Rate from a double to an int.

Solution 2

You need to say that you want an int cast:

double a;
int b = (int) a;
Share:
10,295
Justin
Author by

Justin

Updated on June 04, 2022

Comments

  • Justin
    Justin almost 2 years

    I have a program that uses a formula to calculate the refurb on a unit (parts replaced on cableboxes that were damaged) divided by total units (cableboxes that went through refurb, but did not have any parts replaced). I looked up casting online, and the format for it is:

    int valuetoconvert = Convert.ToInt32;
    

    I'm doing that, but I still get the following error:

    Cannot implicitly convert type 'double to int. An explicit conversion exists(are you missing a cast?)

    What am I doing wrong? Can someone please help? Thank you.

    Here's some of my code:

    private int GetRefurbRate()
    {
    string sql = "";
    double Refurb_Rate;
    int totalRefurb = 0;
    int totalUnits = 0;
    string error_msg = "";
    
    
    sql = "SELECT COUNT(rp.repair_ord) " +
    "FROM " + schema + ".repair_part rp " +
    "WHERE rp.repair_ord = '" + repair_ord + "' ";
    while (true)
    {
    if (!myDb.RunSql(sql, true))
    {
    error_msg = "DBError for getting Refurb Rate";
    break;
    }
    if (myDb.dbRdr.HasRows)
    {
    if (myDb.dbRdr.Read())
    {
    try //Try and Catch are here b/c I originally had everything ints, and and they just caught the 0 exception.
    {
    
    Refurb_Rate = Convert.ToInt32( totalRefurb / totalUnits * 100); //This is where I try to perform the cast.
    
    }
    catch (Exception e)
    {
    Console.WriteLine(e);
    }
    
    }
    
    //int Refurb_Rate = Convert.ToInt32(Refurb_Rate);
    }
    
    break;
    }
    myDb.dbRdr.Close();
    
    if (error_msg != String.Empty)
    {
    MessageBox.Show(error_msg, "Get Refurb Rate",
    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    }