I’m programming in C# using .Net 3.5, trying to control the format in which floats are output as strings.
However, I’m seeing some unexpected behaviour. If my code contains (for example):
float value = 50.8836975;
Edit Sorry, that (deleted) code “sample” was unhelpful. Basically, my question was seeking to explain the results of my debugging statements below when I set a breakpoint after “value” – a C# float – had been assigned the result of a calculation. Jon Skeet‘s answer is exactly what I needed (his first line takes me to task for the unhelpful code).
Then I see the following results when I try various options in my Immediate window:
?value
50.8836975
?value.ToString("G9")
"50.8836975"
?value.ToString("F9")
"50.883700000"
Can anyone explain why my F9-formatted value seems to have lost 3 digits of precision?
Your question is unclear because you’ve given a real value without an
fsuffix, and tried to assign it to afloatvariable. If you’re actually using afloatvariable, then the exact value isIf you’re actually using a
doublevariable, then the exact value is:I get the same results as you for F9 if you use a
float, but not if you use adouble.The reason for the reduced precision is revealed by the documentation for
System.Single(float):I believe
Fis correctly displaying all of the real digits of precision, in an attempt to prevent you from believing that you’ve actually got more information than you have.