1

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"
O. Jones
  • 103,626
  • 17
  • 118
  • 172
pumaikar
  • 78
  • 6
  • 1
    Sigh. Every programmer needs to know about floating-point precision. Have universities stopped teaching it? – O. Jones Mar 20 '20 at 12:01
  • 2
    @O.Jones You're being awfully harsh on someone who has read the documentation which is telling him something completely wrong, so it's only fair they are asking this question. – DavidG Mar 20 '20 at 13:05

1 Answers1

1

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.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • Floating-point numbers are exact. Per the IEEE-754 specification, each floating-point numeric datum (thus excluding NaNs) represents one number exactly. It is floating-point operations, not numbers, that approximate real arithmetic. This includes conversions from decimal numerals to binary floating-point and vice-versa. Understanding this distinction is important for being able to design correct floating-point arithmetic software, calculate error bounds, and write proofs about floating-point arithmetic. – Eric Postpischil Mar 20 '20 at 21:30