Software & Finance





C# - String to Number Conversion Program





Here is the C# source code for string to number conversion.

 

First the length of the string is identified. To handle the negative numbers, the first character is being checked for '-'. If it is '-', then negative number indication flag is set to true (1).

 

The next character ascii value is being deducted from character '0' to get the numeric value. If it is in between 0-9, then it will be stored into the result and when the subsequent character is getting in, the previous value is multiplied by 10. otherwise a non numeric character is found and the return value would be zero.

 

Example String: 5647

Result Value

1st Iteration: 5

2nd Iteration: 5 * 10 + 6 = 56

3rd Iteration: 56 * 10 + 5 = 564

4th Iteration: 564 * 10 + 7 = 5647


 

Source Code


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace sample2

{

   class Program

   {

      static int StringToNumber(string str)

      {

         int result = 0;

         int startIndex = 0;

         int negativeNumber = 0;

        

         char[] buffer = str.ToCharArray();

 

         if(buffer[0] == '-')

         {

               negativeNumber = 1;

               startIndex = 1;

         }

         for(int i = startIndex; i < buffer.Length; i++)

         {

            if(buffer[i] >= '0' && buffer[i] <= '9')

            {

               int digit = buffer[i] - '0';

               result = result * 10 + digit;

            }

            else

               return 0;

         }

         if(negativeNumber == 1)

            result *= -1;

         return result;

      }

 

      static void Main(string[] args)

      { 

         Console.WriteLine("String to Number Conversion Program");

 

         while(true)

         {

            Console.Write("Enter a String (-1 to exit): ");

            string s = Console.ReadLine();

           

           

            int number = StringToNumber(s);

 

            Console.WriteLine("Converted Number: " + number);

 

            if(number == -1)

               break;

         }

      }

   }

}

Output