How to convert number to words in java

前端 未结 27 2814
遇见更好的自我
遇见更好的自我 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:35

    package it.tommasoresti.facebook;
    
    class NumbersToWords {
    
        private static final String ZERO = "zero";
        private static String[] oneToNine = {
                "one", "two", "three", "four", "five", "six", "seven", "height", "nine"
        };
    
        private static String[] tenToNinteen = {
                "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
        };
    
        private static String[] dozens = {
                "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
        };
    
        public static String solution(int number) {
            if(number == 0)
                return ZERO;
    
            return generate(number).trim();
        }
    
        public static String generate(int number) {
            if(number >= 1000000000) {
                return generate(number / 1000000000) + " billion " + generate(number % 1000000000);
            }
            else if(number >= 1000000) {
                return generate(number / 1000000) + " million " + generate(number % 1000000);
            }
            else if(number >= 1000) {
                return generate(number / 1000) + " thousand " + generate(number % 1000);
            }
            else if(number >= 100) {
                return generate(number / 100) + " hundred " + generate(number % 100);
            }
    
            return generate1To99(number);
        }
    
        private static String generate1To99(int number) {
            if (number == 0)
                return "";
    
            if (number <= 9)
                return oneToNine[number - 1];
            else if (number <= 19)
                return tenToNinteen[number % 10];
            else {
                return dozens[number / 10 - 1] + " " + generate1To99(number % 10);
            }
        }
    }
    

    Test

    @Test
    public void given_a_complex_number() throws Exception {
        assertThat(solution(1234567890),
            is("one billion two hundred thirty four million five hundred sixty seven thousand height hundred ninety"));
    }
    

提交回复
热议问题