C# uses several numeric types.
You have already worked with:
int
doubledoubleAn int stores whole numbers.
A double can represent values with fractional parts.
When calculations combine different numeric needs, you may need to convert a value to another numeric type.
Consider:
int goals = 7;
int games = 2;
double average = goals / games;It may look like the result should be:
3.5But the division:
goals / gamesuses two int values.
Integer division produces the whole-number result before it is assigned to the double.
The fractional part is lost.
You can make one operand a double.
For example:
double average = (double)goals / games;Now the division is performed using a floating-point numeric type.
Conceptually:
This can produce:
3.5In:
(double)goalsthe cast tells C# to treat the current numeric value as a double for the calculation.
It does not permanently change the declaration of:
goalsThe original variable can still be declared as:
int goals;Suppose a soccer application calculates average goals per match.
The data may naturally be stored as whole-number counts:
int totalGoals = 7;
int matchesPlayed = 2;The average can be fractional.
That makes a floating-point calculation appropriate:
double averageGoals = (double)totalGoals / matchesPlayed;The conversion supports the meaning of the result.
Sometimes C# can place a whole-number value into a double variable:
int score = 3;
double numericScore = score;But that does not fix a calculation that already used integer division.
This:
double average = totalGoals / matchesPlayed;performs the division first.
If both operands are integers, the fractional portion can already be lost before assignment.
The conversion needs to affect the calculation.
If a jersey number is:
7there is usually no reason to represent it as:
7.0merely because double supports more numeric forms.
Choose types according to the information.
Use conversion when a calculation genuinely needs a different numeric representation.
A player count of:
11is still eleven players whether C# is currently working with:
11or:
11.0The representation changes.
The quantity does not.
For:
double averageGoals = (double)totalGoals / matchesPlayed;read:
This makes the purpose of the conversion clear.
If a field was designed with the wrong type, repeated conversions may be a symptom of that design problem.
For the current activity, use the types provided by the current design and convert only where the calculation requires it.
When a calculation needs a fractional result, make sure the expression uses a numeric type capable of representing that result before the division is completed.