OneBite.Dev - Coding blog in a bite size

Convert Variable From Float To Int In C#

Code snippet for how to Convert Variable From Float To Int In C# with sample and detail explanation

In many programming scenarios, there is a need to switch data types, such as from a float to an int. In this article, we will guide you on how to convert a float variable to an int variable in C# in simple steps.

Code snippet to convert Float to Int

The following illustrates the most straightforward way to convert a float variable to an int in C#:

float myFloat = 9.78f;
int myInt = (int)myFloat;
Console.WriteLine(myInt);

When you run this code, it will print 9.

Code Explanation for Conversion of Float to Int

In this tutorial, our task is to convert a float number to an integer. As the first step, we start by declaring a float variable, myFloat, and assigning it the value 9.78f.

float myFloat = 9.78f;

The letter f is used to represent a floating-point number in C#. If you try to declare a float without the f, the compiler will assume you are trying to create a double.

The next step involves converting the float to an integer. We cast the float variable to an integer using (int) before the variable name. This command instructs the compiler to treat the float as if it were an integer. Note that this operation doesn’t round up the float to the nearest integer, instead it gets rid of the fractional part.

int myInt = (int)myFloat;

Lastly, we print the integer value to the console by invoking the Console.WriteLine() function.

Console.WriteLine(myInt);

So, when we run this code, 9 will be printed on our console because our float value of 9.78 gets cast to 9.

Keep in mind that converting from float to int could lead to data loss if the float contained a value after the decimal point. The explicit conversion offered by C# through casting allows us to control this process.

c-sharp