拼写数字到数字?

时间:2012-08-05 15:54:30

标签: java numbers

任何人都知道一个java库可以使用非常大的拼写数字并将它们转换成数字?如果它也可以做小数位,那就太好了。示例..十到十

2 个答案:

答案 0 :(得分:2)

嗯,为什么不尝试自己的?这里有2个样品可供您选择:

import java.util.*;

public class NumToWords {
        String string;
        String st1[] = { "", "one", "two", "three", "four", "five", "six", "seven",
                        "eight", "nine", };
        String st2[] = { "hundred", "thousand", "lakh", "crore" };
        String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
                        "fifteen", "sixteen", "seventeen", "eighteen", "ninteen", };
        String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
                        "eighty", "ninty" };

        public String convert(int number) {
                int n = 1;
                int word;
                string = "";
                while (number != 0) {
                        switch (n) {
                        case 1:
                                word = number % 100;
                                pass(word);
                                if (number > 100 && number % 100 != 0) {
                                        show("and ");
                                }
                                number /= 100;
                                break;

                        case 2:
                                word = number % 10;
                                if (word != 0) {
                                        show(" ");
                                        show(st2[0]);
                                        show(" ");
                                        pass(word);
                                }
                                number /= 10;
                                break;

                        case 3:
                                word = number % 100;
                                if (word != 0) {
                                        show(" ");
                                        show(st2[1]);
                                        show(" ");
                                        pass(word);
                                }
                                number /= 100;
                                break;

                        case 4:
                                word = number % 100;
                                if (word != 0) {
                                        show(" ");
                                        show(st2[2]);
                                        show(" ");
                                        pass(word);
                                }
                                number /= 100;
                                break;

                        case 5:
                                word = number % 100;
                                if (word != 0) {
                                        show(" ");
                                        show(st2[3]);
                                        show(" ");
                                        pass(word);
                                }
                                number /= 100;
                                break;

                        }
                        n++;
                }
                return string;
        }

        public void pass(int number) {
                int word, q;
                if (number < 10) {
                        show(st1[number]);
                }
                if (number > 9 && number < 20) {
                        show(st3[number - 10]);
                }
                if (number > 19) {
                        word = number % 10;
                        if (word == 0) {
                                q = number / 10;
                                show(st4[q - 2]);
                        } else {
                                q = number / 10;
                                show(st1[word]);
                                show(" ");
                                show(st4[q - 2]);
                        }
                }
        }

        public void show(String s) {
                String st;
                st = string;
                string = s;
                string += st;
        }

        public static void main(String[] args) {
                NumToWords w = new NumToWords();
                Scanner input = new Scanner(System.in);
                System.out.print("Enter Number: ");
                int num = input.nextInt();
                String inwords = w.convert(num);
                System.out.println(inwords);
        }
}

和此:

class constNumtoLetter
  {
      String[] unitdo ={"", " One", " Two", " Three", " Four", " Five",
         " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve",
         " Thirteen", " Fourteen", " Fifteen",  " Sixteen", " Seventeen", 
         " Eighteen", " Nineteen"};
      String[] tens =  {"", "Ten", " Twenty", " Thirty", " Forty", " Fifty",
         " Sixty", " Seventy", " Eighty"," Ninety"};
      String[] digit = {"", " Hundred", " Thousand", " Lakh", " Crore"};
     int r;


      //Count the number of digits in the input number
      int numberCount(int num)
      {
          int cnt=0;

          while (num>0)
          {
            r = num%10;
            cnt++;
            num = num / 10;
          }

            return cnt;
      }


      //Function for Conversion of two digit

      String twonum(int numq)
      {
           int numr, nq;
           String ltr=\"";

           nq = numq / 10;
           numr = numq % 10;

           if (numq>19)
             {
           ltr=ltr+tens[nq]+unitdo[numr];
             }
           else
             {
           ltr = ltr+unitdo[numq];
             }

           return ltr;
      }

      //Function for Conversion of three digit

      String threenum(int numq)
      {
             int numr, nq;
             String ltr = "";

             nq = numq / 100;
             numr = numq % 100;

             if (numr == 0)
              {
              ltr = ltr + unitdo[nq]+digit[1];
               }
             else
              {
              ltr = ltr +unitdo[nq]+digit[1]+" and"+twonum(numr);
              }
             return ltr;

      }

}

 class originalNumToLetter

   {

      public static void main(String[] args) throws Exception
      {

          //Defining variables q is quotient, r is remainder

          int len, q=0, r=0;
          String ltr = " ";
          String Str = "Rupees";
          constNumtoLetter n = new constNumtoLetter();
          int num = Integer.parseInt(args[0]);

          if (num <= 0) System.out.println(\"Zero or Negative number not for conversion");

          while (num>0)
          {

             len = n.numberCount(num);

             //Take the length of the number and do letter conversion

             switch (len)

             {
                  case 8:
                          q=num/10000000;
                          r=num%10000000;
                          ltr = n.twonum(q);
                          Str = Str+ltr+n.digit[4];
                          num = r;
                          break;

                  case 7:
                  case 6:
                          q=num/100000;
                          r=num%100000;
                          ltr = n.twonum(q);
                          Str = Str+ltr+n.digit[3];
                          num = r;
                          break;

                  case 5:
                  case 4:

                           q=num/1000;
                           r=num%1000;
                           ltr = n.twonum(q);
                           Str= Str+ltr+n.digit[2];
                           num = r;
                           break;

                  case 3:


                            if (len == 3)
                                r = num;
                            ltr = n.threenum(r);
                            Str = Str + ltr;
                            num = 0;
                            break;

                  case 2:

                           ltr = n.twonum(num);
                           Str = Str + ltr;
                           num=0;
                           break;

                  case 1:
                           Str = Str + n.unitdo[num];
                           num=0;
                           break;
                  default:

                          num=0;
                          System.out.println(\"Exceeding Crore....No conversion");
                          System.exit(1);


              }
                          if (num==0)
                          System.out.println(Str+\" Only");
            }

         }

      }

编辑:

此示例最多可转换为数十亿美元:

import java.text.DecimalFormat;

public class EnglishNumberToWords {

  private static final String[] tensNames = {
    "",
    " ten",
    " twenty",
    " thirty",
    " forty",
    " 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 static 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 static String convert(long number) {
    // 0 to 999 999 999 999
    if (number == 0) { return "zero"; }

    String snumber = Long.toString(number);

    // pad with "0"
    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    snumber = df.format(number);

    // XXXnnnnnnnnn 
    int billions = Integer.parseInt(snumber.substring(0,3));
    // nnnXXXnnnnnn
    int millions  = Integer.parseInt(snumber.substring(3,6)); 
    // nnnnnnXXXnnn
    int hundredThousands = Integer.parseInt(snumber.substring(6,9)); 
    // nnnnnnnnnXXX
    int thousands = Integer.parseInt(snumber.substring(9,12));    

    String tradBillions;
    switch (billions) {
    case 0:
      tradBillions = "";
      break;
    case 1 :
      tradBillions = convertLessThanOneThousand(billions) 
      + " billion ";
      break;
    default :
      tradBillions = convertLessThanOneThousand(billions) 
      + " billion ";
    }
    String result =  tradBillions;

    String tradMillions;
    switch (millions) {
    case 0:
      tradMillions = "";
      break;
    case 1 :
      tradMillions = convertLessThanOneThousand(millions) 
      + " million ";
      break;
    default :
      tradMillions = convertLessThanOneThousand(millions) 
      + " million ";
    }
    result =  result + tradMillions;

    String tradHundredThousands;
    switch (hundredThousands) {
    case 0:
      tradHundredThousands = "";
      break;
    case 1 :
      tradHundredThousands = "one thousand ";
      break;
    default :
      tradHundredThousands = convertLessThanOneThousand(hundredThousands) 
      + " thousand ";
    }
    result =  result + tradHundredThousands;

    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result =  result + tradThousand;

    // remove extra spaces!
    return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
  }

  /**
   * testing
   * @param args
   */
  public static void main(String[] args) {
    System.out.println("*** " + EnglishNumberToWords.convert(0));
    System.out.println("*** " + EnglishNumberToWords.convert(1));
    System.out.println("*** " + EnglishNumberToWords.convert(16));
    System.out.println("*** " + EnglishNumberToWords.convert(100));
    System.out.println("*** " + EnglishNumberToWords.convert(118));
    System.out.println("*** " + EnglishNumberToWords.convert(200));
    System.out.println("*** " + EnglishNumberToWords.convert(219));
    System.out.println("*** " + EnglishNumberToWords.convert(800));
    System.out.println("*** " + EnglishNumberToWords.convert(801));
    System.out.println("*** " + EnglishNumberToWords.convert(1316));
    System.out.println("*** " + EnglishNumberToWords.convert(1000000));
    System.out.println("*** " + EnglishNumberToWords.convert(2000000));
    System.out.println("*** " + EnglishNumberToWords.convert(3000200));
    System.out.println("*** " + EnglishNumberToWords.convert(700000));
    System.out.println("*** " + EnglishNumberToWords.convert(9000000));
    System.out.println("*** " + EnglishNumberToWords.convert(9001000));
    System.out.println("*** " + EnglishNumberToWords.convert(123456789));
    System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
    System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));

    /*
     *** zero
     *** one
     *** sixteen
     *** one hundred
     *** one hundred eighteen
     *** two hundred
     *** two hundred nineteen
     *** eight hundred
     *** eight hundred one
     *** one thousand three hundred sixteen
     *** one million 
     *** two millions 
     *** three millions two hundred
     *** seven hundred thousand 
     *** nine millions 
     *** nine millions one thousand 
     *** one hundred twenty three millions four hundred 
     **      fifty six thousand seven hundred eighty nine
     *** two billion one hundred forty seven millions 
     **      four hundred eighty three thousand six hundred forty seven
     *** three billion ten
     **/
  }
}

<强>参考文献:

答案 1 :(得分:2)

令人惊讶的是,似乎还没有Java库可以解决这个问题。由于我发现问题评论中的Python解决方案很优雅,我将其转换为Java:

<强> Text2Digit.java

public class Text2Digit {

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

    final static String[] tens = { "", "", "twenty", "thirty", "forty",
            "fifty", "sixty", "seventy", "eighty", "ninety" };

    final static String[] scales = { "hundred", "thousand", "million",
            "billion", "trillion" };

    final static Map<String, ScaleIncrement> numWords = new HashMap<>();

    static {
        numWords.put("and", ScaleIncrement.valueOf(1, 0));
        for (int i = 0; i < units.length; i++)
            numWords.put(units[i], ScaleIncrement.valueOf(1, i));

        for (int i = 0; i < tens.length; i++)
            numWords.put(tens[i], ScaleIncrement.valueOf(1, i * 10));

        for (int i = 0; i < scales.length; i++) {
            int exponent = (i * 3 == 0) ? 2 : i * 3;
            numWords.put(scales[i],
                    ScaleIncrement.valueOf((int) Math.pow(10, exponent), 0));
        }
    }

    public static long convert(String text) {

        long current = 0;
        long result = 0;
        for (String word : text.split(" ")) {

            if (!numWords.containsKey(word))
                throw new RuntimeException("Illegal word:" + word);

            long scale = numWords.get(word).scale;
            long increment = numWords.get(word).increment;
            current = current * scale + increment;
            if (scale > 100) {
                result += current;
                current = 0;
            }
        }

        return result + current;
    }

}

<强> ScaleIncrement.java

public class ScaleIncrement {

    long scale;
    long increment;

    private ScaleIncrement() {}

    public static ScaleIncrement valueOf(long scale, long increment) {
        ScaleIncrement result = new ScaleIncrement();
        result.scale = scale;
        result.increment = increment;
        return result;
    }

}

<强>测试

public static void main(String[] args) {

    System.out.println(convert("seven billion one"
            + " hundred million thirty one thousand"
            + " three hundred thirty seven"));
}

<强>输出

  

7100031337