How to convert number to words in java

前端 未结 27 2785
遇见更好的自我
遇见更好的自我 2020-11-21 23:53

We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. B

27条回答
  •  醉酒成梦
    2020-11-22 00:29

    class NumberToWord {
        private static Map numbers = new HashMap();
        private static Set numberSet = new TreeSet(new Comparator() {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
    
        static {
            init();
            numberSet.addAll(numbers.keySet());
        }
    
        public static void main(String[] args) {
            System.out.println(getNumberInWord(1898765));
        }
    
        /*
         * convert positive numbers in word format number > 0 only
         */
        static String getNumberInWord(int number) {
            StringBuilder word = new StringBuilder();
            for (Integer n : numberSet) {
                if (number > 0 && number >= n) {
                    int div = number / n;
                    String strNum = numbers.get(div);
                    if (strNum == null) {
                        word.append(getNumberInWord(div));
                    }
                    // for less than 100, we don't need to say 1
                    if (strNum != null && (div > 1 || n > 100))
                        word.append(strNum + " ");
    
                    word.append(numbers.get(n) + " ");
                    number = number % n;
                }
            }
            return word.toString();
        }
    
        static void init() {
            numbers.put(0, "Zero");
            numbers.put(1, "One");
            numbers.put(2, "Two");
            numbers.put(3, "Three");
            numbers.put(4, "Four");
            numbers.put(5, "Five");
            numbers.put(6, "Six");
            numbers.put(7, "Seven");
            numbers.put(8, "Eight");
            numbers.put(9, "Nine");
            numbers.put(10, "Ten");
            numbers.put(11, "Eleven");
            numbers.put(12, "Twelve");
            numbers.put(13, "Thirteen");
            numbers.put(14, "Fourteen");
            numbers.put(15, "Fifteen");
            numbers.put(16, "Sixteen");
            numbers.put(17, "Seventeen");
            numbers.put(18, "Eighteeen");
            numbers.put(19, "Nineteen");
            numbers.put(20, "Twenty");
            numbers.put(30, "Thirty");
            numbers.put(40, "Forty");
            numbers.put(50, "Fifty");
            numbers.put(60, "Sixty");
            numbers.put(70, "Seventy");
            numbers.put(80, "Eighty");
            numbers.put(90, "Ninty");
            numbers.put(100, "Hundred");
            numbers.put(1000, "Thousand");
            numbers.put(1000000, "Million");
            numbers.put(100000000, "Billion");
        }
    
    }
    

提交回复
热议问题