Search code examples
c#floating-pointprecisiontostringieee-754

Parsing float to string gives different result compare to Microsoft Docs


My code:

float st = -195489100.8377F;  

Console.WriteLine("   {0,5}: {1}", "F", st.ToString("F", CultureInfo.GetCultureInfo("en-US")));

// output:
//        F: -195489100.00

But on Docs.Microsoft is result:

//              F: -195489100.84

I tried it also without CultureInfo.GetCultureInfo("en-US") but it is same.

My goal is parse this float to string:

float st = 16777215.255f;

my result is 16777220.00 using above method. But i need exactly

"16777215.255"

Solution

  • In the C# language, the float datatype uses 32 bits to store. It's 32-bit IEEE-754. That format gives about 7 digits of precision. So when you use float st = 16777215.255f; you give more bits of precision than the format can store, so when you display it you get 16777220.00.

    You may be able to get the precision you need with the double datatype. That's 64-bit IEEE-754, and has about fifteen digits of precision. It's the datatype Javascript uses for numbers, by the way.

    But, beware. You say you need "exactly" some particular number. Floating-point values are not exact. They are approximations. If you need exact values, consider using a decimal data type.