0

I have this program that gets all the numbers from a double variable, removes decimal marks and minuses and adds every digit separately. Here is is:

static void Main(string[] args)
    {

            double input = double.Parse(Console.ReadLine());

                char[] chrArr = input.ToString().ToCharArray();

                input = 0;

                foreach (var ch in chrArr)
                {
                    string somestring = Convert.ToString(ch);
                    int someint = 0;
                    bool z = int.TryParse(somestring, out someint);
                    if (z == true)
                    {
                        input += (ch - '0');
                    }
                }

The problem is for example when I enter "9999999999999999999999999999999...." and so on, it gets represented as 1.0E+254 and what so my program just adds 1+0+2+5+4 and finishes. Is there efficient way to make this work properly ? I tried using string instad of double, but it works too slow..

Martin Dzhonov
  • 1,021
  • 4
  • 15
  • 28
  • 2
    You should know that a `double` won't be able to hold that number in the first place. Look for `BigDecimal` instead. – Jeroen Vannevel Nov 01 '13 at 13:55
  • http://stackoverflow.com/questions/1319191/how-to-convert-double-to-string-without-the-power-to-10-representation-e-05 – algreat Nov 01 '13 at 13:57
  • possible duplicate of [Double to string conversion without scientific notation](http://stackoverflow.com/questions/1546113/double-to-string-conversion-without-scientific-notation) – David Arno Nov 01 '13 at 13:58
  • So your base goal is to add up all of the numeric digits in a limitless string? – D Stanley Nov 01 '13 at 14:32

3 Answers3

6

You can't store "9999999999999999999999999999999..." as a double - a double only has 15 or 16 digits of precision. The compiler is giving you the closest double it can represent to what you're asking, which is 1E254.

I'd look into why using string was slow, or use BigInteger

D Stanley
  • 149,601
  • 11
  • 178
  • 240
3

As other answers indicate, what's stored will not be exactly the digits entered, but will be the closest double value that can be represented.

If you want to inspect all of it's digits though, use F0 as the format string.

char[] chrArr = input.ToString("F0").ToCharArray();
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

You can store a larger number in a Decimal as it is a 128 bit number compared to the 64 bit of a Double.

But there is obviously still a limit.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73