doing an operation on two numbers will give you a different output type depending on what the types of the operands are.
- an "operation" is something like "addition" (
+
) or division (/
). - an "operand" is one of the things you're doing the operation on.
for example, in 3 - 2
, 3 is the first operand, 2 is the second operand, and subtraction (-
) is the operation.
For our case, we're working with 2 types:
double
s (your decimal values2.0
. "double" is short for "double-precision floating point" number)int
An integer! It can't represent decimals. If you convert a decimal like2.5
into an int with a cast(int)2.5
, it truncates to2
, meaning you lose the decimal!
Now, when you go to do math with int
s, particularly division, the fact that they can't represent decimals matters!
- If you do
3/4
, you'll get0
, even though the real-world answer is0.75
! Whatever decimal part would be left over always disappears if both operands are integers. - If you were to do the same with doubles, however, things work fine! You can try it by appending
d
or.0
to the end of your numbers to make them doubles. (3d/4d
yields0.75
!)
Now, when one operand is an int
, and the other is a double
, things get interesting. The designers of C# had to make a decision: When do you math with two different types, how do you choose what the type of the result is?
They chose to keep the type with greater precision. (The type with greater precision is the type that lets you get more specific with your values, in this case, double
is the winner!)
So, for this reason, any time you do 2d + 3
or 3/4d
, you'll get a double
as your result, and you'll have a decimal!
This idea is sometimes referred to as "Numeric Promotion". You can read about all the places it happens in C# in this article.