2

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?

4
  • 3
    Are you sure that's the exact value you have stored? Commented Feb 15, 2010 at 21:25
  • 4
    If you want exact values, floats are a really bad choice for a data type. Commented Feb 15, 2010 at 21:29
  • 1
    If you want exact decimal representations, you should be using Decimals. Commented Feb 15, 2010 at 21:39
  • 2
    The float type can only reliably store 7 significant digits. You'll never get the last two digits in that number. Commented Feb 16, 2010 at 3:40

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

Could you provide a summary of the article in case it expires?
1

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.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.