C# 将浮点转换为整数

C# 将浮点转换为整数,c#,C#,所以我有一个项目正在做。这是我唯一的错误: 无法将类型“float”隐式转换为“int” 我多少能理解这意味着什么。我只是需要帮助将我的浮点值转换为int 这只是其中一个浮动的示例: float key = 0.5f; int key = 53; 以下是具体的代码部分: // price in scrap, e.g. 29 / 9 = 3.33 ref static int BuyPricePerTOD = 21; // price in scrap, e.g. 31 / 9 = 3.55 r

所以我有一个项目正在做。这是我唯一的错误:

无法将类型“float”隐式转换为“int”

我多少能理解这意味着什么。我只是需要帮助将我的浮点值转换为int

这只是其中一个浮动的示例:

float key = 0.5f;
int key = 53;
以下是具体的代码部分:

// price in scrap, e.g. 29 / 9 = 3.33 ref
static int BuyPricePerTOD = 21;
// price in scrap, e.g. 31 / 9 = 3.55 ref
static float SellPricePerTOD = BuyPricePerTOD + 0.5F;

static int BuyPricePerKey = 53;
static float SellPricePerKey = BuyPricePerKey + 0.5F;

static int TimerInterval = 170000;
static int InviteTimerInterval = 2000;

int UserWeapAdded,UserScrapAdded,UserRecAdded,UserRefAdded,
    UserKeysAdded,UserTODAdded,BotTODsAdded,BotKeysAdded,
    BotScrapAdded,BotRecAdded,BotRefAdded,InventoryMetal,
    InventoryScrap,InventoryRec,InventoryRef,InventoryKeys,
    InventoryTOD,PreviousTODs,PreviousKeys,WhileLoop,InvalidItem = 0;

float UserMetalAdded, BotMetalAdded, OverpayNumKeys,
    OverpayNumTOD, ExcessInScrapKey, ExcessInScrapTOD = 0.0F;
double ExcessRefinedKey, ExcessRefinedTOD = 0.0;
试试这个:

int numInt = (int)Math.Ceiling(numFloat);

顺便说一下,您可能需要
Math.Round()
Math.Floor()

例如:

float numFloat = 1.5f;
int testCeiling = (int)Math.Ceiling(numFloat);
int testFloor = (int)Math.Floor(numFloat);
int testRound = (int)Math.Round(numFloat);

Console.WriteLine("testCeiling = {0}", testCeiling.ToString());
Console.WriteLine("testFloor = {0}", testFloor.ToString());
Console.WriteLine("testRound= {0}", testRound.ToString());
输出:

testCeiling = 2
testFloor = 1
testRound= 2
首先,有整数和浮点数。整数总是整数,例如
0
1
-32
42
1337
。另一方面,浮点数可以有小数部分:
0
1
-32.1
42.7
123.456788
都是有效的浮点数

在整数(
int
)和浮点数(
float
)之间转换时,可以执行以下操作:

int someInt = 42;
float someFloat = someInt;  // 42.0f
但你不能这样做:

float someFloat = 42.7f;
int someInt = someFloat;    // ?
可以进行第一次转换的原因是,将整数(
int
)转换为浮点数(
float
)不会改变数字。这是一种安全的转换,因此可以隐式进行

不允许进行第二次转换的原因是,将浮点数(可能有小数部分)转换为整数(从来没有小数部分)必须删除该数字的小数部分,即它变成不同的数字。这是不安全的,因此只能显式执行


要显式地将一种类型的数字转换为另一种类型,可以使用强制转换。这是数字前面的括号,带有要将其转换为的数字类型

float someFloat = 42.7f;
int someInt = (int)someFloat;               // 42
请注意,浮点数的小数部分已删除。就好像它被四舍五入到了零。如果要将浮点数四舍五入到最接近的整数,请使用


你能展示一下你到目前为止所做的一些代码吗?@user3325320。。int _value=Convert.ToInt32(键);你想四处转转吗?还是只想截断?例如
1.8
四舍五入为
2
,但截断为
1
。这是需要转换的部分。此外,数字需要精确。我不能圆化它或截断它。但是我也不使用小数。@user3325320,
int
s不能存储小数,因此整数“向零舍入”这个名称是一个矛盾修饰法。我的意思是这不是一回事。你的解释模棱两可,因为“向下舍入”和“向零舍入”是负数的相反方向。它们对于正数来说是一样的。
float someFloat = 42.7f;
int someInt = (int)Math.Round(someFloat);   // 43