That you are rounding, not formatting :-)
you don't need the Math.Round
, you need:
Console.WriteLine("Total Cost = £ {0:F2}", totalCost);
You can look at it in this way: the computer represent internally numbers in some formats. These formats are normally binary formats, and aren't "intellegible" by "mere mortals". double
is one of these formats. It's a fixed-length format, so every double
is 8 bytes long. When you want to print it somewhere, you have to "stringify" it (convert it to a format intellegible for humans). In C#/.NET this is normally done with the ToString()
method that all the objects have.
Now, in a double
1.0 == 1.00 == 1. The extra zeros aren't saved (because they normally aren't important)
Math.Round
"produces" a double
with a maximum number of decimals (we will ignore the vagaries of double
). So Math.Round(1.222, 2) == 1.22
, but Math.Round(1.0, 2) == 1
So Math.Round
is a function that from a double
returns a double
.
Console.WriteLine
is something different. In this case it takes a double
and string
ify it (and show it to the console screen). When you stringify a number and tell the Console.WriteLine
that you want 2 decimals after the .
, it will show 2 decimals, even if there are zero decimals. So Console.WriteLine("{0:F2}", 1)
will print 1.00
. Probably Console.WriteLine
uses the ToString
method of double
to do it. So in truth, it would be better to analyze the ToString
method of double
, because Console.WriteLine("Total Cost = £ {0:F2}", totalCost)
is probably very similar internally to Console.WriteLine("Total Cost = £ {0}", totalCost.ToString("F2"));
I was forgetting. Do as AVD told you in a comment to your post. float
and double
are probably two of the greatest evils of Information Technology.