c# - 如何将 double 转换为 int?

标签 c# types casting double int

我有一个程序使用一个公式来计算一个单元的翻新(在损坏的有线电视盒上更换的部件)除以总单元(经过翻新但没有更换任何部件的有线电视盒)。我在网上查了casting,格式是:

int valuetoconvert = Convert.ToInt32;

我正在这样做,但我仍然收到以下错误:

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

我做错了什么?有人可以帮忙吗?谢谢。

这是我的一些代码:

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);
}

最佳答案

你说你想要一个 int 转换,但实际上你需要转换为一个 double。您可以这样做(Example Code):

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

否则,您需要将 Refurb_Ratedouble 更改为 int

关于c# - 如何将 double 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5625038/

相关文章:

java - 无法从 List<List> 转换为 List<List<?>>

java - 提供类型安全的方法有用吗?

javascript - javascript如何识别对象

c# - 如何在一个Form上同时为两个不同的Control设置两种不同的Culture?

c# - Lazy<T> 是否应该比 getter 中的惰性初始化更受欢迎?

c# - WPF:在附加属性中,如何等待可视化树正确加载?

c++ - 是否有 decltype 的快捷方式

c# - 在幕后,C#/.NET 中的十进制值类型发生了什么?

c# - unity中如何使用接口(interface)

flutter - Dart 泛型类型作为类成员函数的类型