Software & Finance





Java - String to Number Conversion Program





Here is the Java 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


import java.lang.*;

import java.util.*;

import java.io.*;

 

 

class StringToNumber

{

      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 public String ReadString()

      {

            try

            {

                  String inpString = "";

                  InputStreamReader input = new InputStreamReader(System.in);

                  BufferedReader reader = new BufferedReader(input);

                  return reader.readLine();

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

            return "";

      }

 

 

 

      public static void main(String[] args)

      { 

         System.out.println("String to Number Conversion Program");

 

         while(true)

         {

            System.out.print("Enter a String (-1 to exit): ");

            String s = ReadString();

           

            int number = StringToNumber(s);

 

            System.out.println("Converted Number: " + number);

 

            if(number == -1)

               break;

         }

      }

}

Output