How to convert number to words in java

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

    This is another way...(with limited range)

    public static String numToWord(Integer i) {
    
     final  String[] units = { "Zero", "One", "Two", "Three",
            "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
            "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
            "Seventeen", "Eighteen", "Nineteen" };
     final  String[] tens = { "", "", "Twenty", "Thirty", "Forty",
            "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
        if (i < 20)
            return units[i];
        if (i < 100)
            return tens[i / 10] + ((i % 10 > 0) ? " " + numToWord(i % 10) : "");
        if (i < 1000)
            return units[i / 100] + " Hundred"
                    + ((i % 100 > 0) ? " and " + numToWord(i % 100) : "");
        if (i < 1000000)
            return numToWord(i / 1000) + " Thousand "
                    + ((i % 1000 > 0) ? " " + numToWord(i % 1000) : "");
        return numToWord(i / 1000000) + " Million "
                + ((i % 1000000 > 0) ? " " + numToWord(i % 1000000) : "");
    }
    

提交回复
热议问题