In the example below the number 12345678.9 loses accuracy when it’s converted to a string as it becomes 1.234568E+07. I just need a way to preserve the accuracy for large floating point numbers. Thanks.
Single sin1 = 12345678.9F;
String str1 = sin1.ToString();
Console.WriteLine(str1); // displays 1.234568E+07
If you want to preserve decimal numbers, you should use
System.Decimal. It’s as simple as that.System.Singleis worse thanSystem.Doublein that as per the documentation:You haven’t just lost information when you’ve converted it to a string – you’ve lost information in the very first line. That’s not just because you’re using
floatinstead ofdouble– it’s because you’re using a floating binary point number.The decimal number 0.1 can’t be represented accurately in a binary floating point system no matter how big you make the type…
See my articles on floating binary point and floating decimal point for more information. Of course, it’s possible that you should be using
doubleor evenfloatand just not caring about the loss of precision – it depends on what you’re trying to represent. But if you really do care about preserving decimal digits, then use a decimal-based type.