This is follow up for my last question about converting string to float
I have this value stored in a float variable: 33.9112625 (it's thirty three) and I need to convert it to string and get the exact value but I'm unable to do so. float.ToString( CultureInfo.InvariantCulture) gives me "33.91126" as result. I tried .ToString("G"), "G7" and CultureInfo.InvariantCulture.NumberForm开发者_如何学运维at but they didn't help. How can I convert a float to string and get the exact same value?
First, you aren't saving "exact" values in a float (System.Single). For details, see David Goldberg's article on floating point precision.
That being said, if you want to convert this, you'll need to specify extra precision to Single.ToString(). By using "G", you get the default precision, which is 7. In your case, to see the value you've shown, you'd need 9, so you could use "G9".
Jon Skeet provides an article explaining this along with C# code to print the exact representation.
Try changing it to Decimal
type, I tried it using float
but it would only show 5 decimal places.
decimal d = 33.9112625M; Console.WriteLine("{0}", d.ToString(System.Globalization.InvariantCulture));
Hope this helps, Best regards, Tom.
精彩评论