This is caused by two PowerShell behaviors:
To understand the details, we start by observing that, when “4.2” is properly converted to IEEE-754 basic binary floating-point with round-to-nearest, the result is exactly 4.19999980926513671875 for float
and 4.20000000000000017763568394002504646778106689453125 for double
.
To display the float
result, PowerShell (in effect) formats it with seven decimal digits, producing “4.200000”, and then suppresses trailing zeros, producing “4.2”.
PowerShell does arithmetic using double
, not float
. When you add 3, the result is a double
, not a float
. The resulting value is 7.19999980926513671875, and, since this is a double
, PowerShell formats it with the default double
format. In this case, it formats it with 15 digits, producing “7.19999980926514”.
For [double]"4.2" + 3
, on the other hand, the result is 7.20000000000000017763568394002504646778106689453125. When this is formatted with 15 digits, the result is “7.20000000000000”. Suppressing trailing zeros leaves “7.2”.
(Note that such simple results are not always the case after arithmetic. There can be situations where the addition causes some rounding of low bits, with the result that the computed result will not finish with trailing zeros when formatted with 15 digits.)