Game Development Reference
In-Depth Information
Here, the
float
type uses the least amount of memory. The
double
type can store
very large numbers, and with high precision. The
decimal
type is even more precise,
but it cannot contain values as high as the
float
or
double
types.
Every type has its own target application. The
decimal
type is useful for financial
calculations, or in games for very precise physical calculations. The
double
type is
used for many mathematical calculations.
float
is used if precision is not that impor-
tant, but saving memory use is. When we write a numerical value in our program
somewhere, we can explicitly indicate that it is of type
float
. For example:
float
speed = 0.3f;
Here the
f
written behind the value 0
.
3 indicates that the value is of type
float
.Thisis
useful, because we also want to store that value in a variable of type
float
. Suppose
that we would have written the following:
float
speed = 0.3;
This instruction would actually give a compiler error! Why? Because the compiler
interprets the value 0.3 as being of type
double
, and by performing the assignment,
this value would have to be stored in a variable of type
float
. Since
float
uses half
of the memory as
double
, it does not fit, so the compiler complains. You may think
that this is only to annoy the programmers. After all, the compiler should be able to
understand that the
double
0.3 value should be converted into a
float
value, and just
do it automatically, right? If you think about it, that could lead to very dangerous
situations. Suppose that you are a very rich person, and your bank uses C# to store
how much money you have on your bank account:
double
account = 12345678912345;
Now you want to transfer this money to another account. However, a not so smart
programmer accidentally uses the
float
type for that:
float
newaccount = account;
Now, because of the reduced precision of the
float
type, the value that is actually
stored is 12,345,678,900,000. In other words, you just lost 12,345 dollars! When
assigning a value to a variable may result in the loss of information, the compiler
generates an error so that you are aware of it. If you still would like to perform the
assignment, you have to state explicitly that you want to convert the value into a
value of type
float
:
float
newaccount = (
float
)account;
When you convert an expression of a certain type into an expression of another type,
this is called a
cast
. A cast is performed by writing the type that we want to cast to
between parentheses in front of the expression. Casting is only possible between