views:

482

answers:

4

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.NumberFormat but they didn't help. How can I convert a float to string and get the exact same value?

+6  A: 

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".

Reed Copsey
+4  A: 

Jon Skeet provides an article explaining this along with C# code to print the exact representation.

Eric J.
+1  A: 

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.

tommieb75
At least it would be favourable to put a comment in as to why it was downvoted? Ignorant...you'd do the exact same thing I'm sure if you cared enough to improve yourself!
tommieb75
A: 

Turns out I wasn't actually storing that exact value in float variable, I realized it thanks to the article posted by Eric J

I've changed my variable type from float to double and problem solved.

Armagan
Then you should accept Eric J's answer.
Dietrich Epp
You're right, I should've done so.
Armagan