If I assign the value 0.1 to a float:
float f = 0.1;
The actual value stored in memory is not an exact representation of 0.1, because 0.1 is not a number that can be exactly represented in single-precision floating-point format. The actual value stored - if I did my maths correctly - is
0.100000001490116119384765625
But I can't identify a way to get C# to print out that value. Even if I ask it to print the number to a great many decimal places, it doesn't give the correct answer:
// prints 0.10000000000000000000000000000000000000000000000000
Console.WriteLine(f.ToString("F50"));
How can I print the exact value stored in a float; the value actually represented by the bit-pattern in memory?
EDIT: It has been brought to my attention elsewhere that you can get the behaviour I ask for using standard format strings... on .NET Core and .NET 5.0. So this question is .NET Framework specific, I guess.
Oops, this answer relates to C, not C#.
Leaving it up as it may provide C# insight as the languages have similarities concerning this.
To print the value of a
floatin decimal with sufficient distinctive decimal places from all otherfloat:To print the value in decimal with all decimal places places is hard - and rarely needed. Code could use a greater precision. Past a certain point (e.g. 20 significant digits),
big_valuemay lose correctness in the lower digits withprintf(). This incorrectness is allowed in C and IEEE 754:To print the value in decimal with all decimal places places for all
float, write a helper function. Example.