6 Replies Latest reply on Mar 10, 2008 2:40 PM by 807601

    number (with comma) to word conversion

    807601
      Hi Folks,

      I am new to java and I really wish for your help. The program I have below only accepts number without comma as the input.

      May I ask for your help on how I can tweak this so that the input accepts comma (eg. 203,500).

      Thanks a ton!

      The code is as follows....

      import java.io.*; //imports java.io class

      class EnglishDecimalFormat {
      private static final String[] majorNames = {
      "",
      " thousand",
      " million",
      " billion",
      " trillion",
      " quadrillion",
      " quintillion"
      };

      private static final String[] tensNames = {
      "",
      " ten",
      " twenty",
      " thirty",
      " fourty",
      " fifty",
      " sixty",
      " seventy",
      " eighty",
      " ninety"
      };

      private static final String[] numNames = {
      "",
      " one",
      " two",
      " three",
      " four",
      " five",
      " six",
      " seven",
      " eight",
      " nine",
      " ten",
      " eleven",
      " twelve",
      " thirteen",
      " fourteen",
      " fifteen",
      " sixteen",
      " seventeen",
      " eighteen",
      " nineteen"
      };

      private String convertLessThanOneThousand(int number) {
      String soFar;

      if (number % 100 < 20){
      soFar = numNames[number % 100];
      number /= 100;
      }
      else {
      soFar = numNames[number % 10];
      number /= 10;

      soFar = tensNames[number % 10] + soFar;
      number /= 10;
      }
      if (number == 0) return soFar;
      return numNames[number] + " hundred" + soFar;
      }

      public String convert(int number) {
      /* special case */
      if (number == 0) { return "zero"; }

      String prefix = "";

      if (number < 0) {
      number = -number;
      prefix = "negative";
      }

      String soFar = "";
      int place = 0;

      do {
      int n = number % 1000;
      if (n != 0){
      String s = convertLessThanOneThousand(n);
      soFar = s + majorNames[place] + soFar;
      }
      place++;
      number /= 1000;
      } while (number > 0);

      return (prefix + soFar).trim();
      }

      public static void main(String[] args) throws IOException {
           BufferedReader stdin = new BufferedReader(
                new InputStreamReader(System.in));

      EnglishDecimalFormat f = new EnglishDecimalFormat();
      System.out.print("Enter the number: ");
      int x = Integer.parseInt(stdin.readLine());
      System.out.println("Converted: " + f.convert(x));
      }
      }