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