Convert Float to Int

c#

Solution

Firstly, there are integers and floating-point numbers. Integers are always whole numbers, such as `0`, `1`, `-32`, `42` and `1337`. On the other hand, floating-point numbers can have a fractional part: `0`, `1`, `-32.1`, `42.7` and `123.456788` are all valid floating-point numbers.

When converting between integers (`int`) and floating-point (`float`) numbers, you can do this:

int someInt = 42;
float someFloat = someInt;  // 42.0f

But you can't do this:

float someFloat = 42.7f;
int someInt = someFloat;    // ?

The reason the first conversion is possible, is that converting the integer number (`int`) to a floating-point number (`float`) does not change the number. It is a safe conversion, and therefore can be done implicitly.

The reason the second conversion is not allowed, is that converting the floating-point number (which may have a fractional part) to an integer number (that never has a fractional part) must drop the fractional part of the number, i.e. it becomes a different number. This is not safe, and can therefore only be done explicitly.

To explicitly convert one type of number to another, you use a cast. That's the parentheses before the number with the type of the number that you want to convert it to.

float someFloat = 42.7f;
int someInt = (int)someFloat;               // 42

Note that the fractional part of the floating-point number was dropped. It's as if it has been rounded towards zero. If you want to round the floating-point number to the nearest whole number, use the `Math.Round` method.

float someFloat = 42.7f;
int someInt = (int)Math.Round(someFloat);   // 43

Problem

So I've got a project I'm working on. This is the only error I have: Cannot implicitly convert type 'float' to 'int'. I understand somewhat what that means. I just need help converting my float to int. This is just an example of one of the floats: ``` float key = 0.5f; int key = 53; ``` Here's the specific code section: ``` // 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; ```

Original source