• Register
262 points

In C#, after declaring a variable is once, it cannot be declared again or assigned a worth of another type unless that type is implicitly convertible to the variable's type. Because C# is statically-typed at the build time.

The float can't be implicitly converted to int (Int32). So that, after you declare i as an int, you can't assign the float 3.15159 within variable i. To perform a conversion without a risk of losing information, the compiler requires that you simply perform a particular conversion, which is named a cast. In type casting, a value type is converted into another value type by a programmer using casting operator. Whereas in type conversion, a value type is converted into another value type by the compiler. A cast is performed by informing explicitly the compiler that you simply make the conversion which you're aware that data loss might occur, or the cast may fail at runtime.

Cast float to int

To perform a cast from float to int (Int32), specify the type int that simply you are casting to inside the parentheses before the value or variable to be converted. In this conversion, only the part of integer i.e. from most significant bit to immediate before of floating point will be converted into integer value.

Code Example

using System;
class Program
    static void Main()
        float.TryParse(Console.ReadLine(), out float myFloat);
        int i = CastToFloat(myFloat);
    static int CastToFloat(float floatValue)
        int i = (int)floatValue;
        return i;