4

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 

3 Answers 3

15

If you want to preserve decimal numbers, you should use System.Decimal. It's as simple as that. System.Single is worse than System.Double in that as per the documentation:

By default, a Single value contains only 7 decimal digits of precision, although a maximum of 9 digits is maintained internally.

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 float instead of double - 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 double or even float and 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.

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

Comments

3

You can't. Simple as that. In memory your number is 12345679. Try the code below.

Single sin1 = 12345678.9F; String str1 = sin1.ToString("r"); // Shows "all" the number Console.WriteLine(sin1 == 12345679); // true Console.WriteLine(str1); // displays 12345679 

Technically r means (quoting from MSDN) round-trip: Result: A string that can round-trip to an identical number. so in reality it isn't showing all the decimals. It's only showing all the decimals needed to distinguish it from other possible values of Single. If you want to show all the decimals use F20.

If you want more precision use double or better use decimal. float has the precision that it has. As we say in Italy "Non puoi spremere sangue da una rapa" (You can't squeeze blood from a turnip)

Comments

0

You could also write an IFormatProvider for your purpose - but the precision doesn't get any better unless you use a different type. this article may help - http://www.csharp-examples.net/string-format-double/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.