Inspired by this question, the following doesn’t do what I’d expect it to:
float myFloat = 0.6;
Console.WriteLine(myFloat);
// Output: 0.6
I’d expect the above to print out 0.60000002384185791 (the floating point representation of 0.6) – clearly there is some mechanism here which is making this work when in fact it shouldn’t (although as you can see from the linked question it sometimes doesn’t work)
What is this mechanism and how does it work?
If you look at the implementation of
Console.WriteLine, you’ll see that it ends up callingToStringon the value with a defaultFormatProvider. I.e. the result you’re seeing is how the number appears when formatted using this format provider.While it doesn’t explain the details of how the result is produced, it does show that
Console.WriteLinegoes through some formatting of the value before printing it.