Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to string and getting exact value

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?

like image 642
dstr Avatar asked Sep 23 '26 07:09

dstr


1 Answers

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

like image 61
Reed Copsey Avatar answered Sep 26 '26 02:09

Reed Copsey