Int to English words in Java

后端 未结 4 1172
情歌与酒
情歌与酒 2020-12-07 04:20

Here I am to ask something weird.

I would like to ask that is there any method/logic by which we can convert an integer value to a string value containing the Englis

相关标签:
4条回答
  • 2020-12-07 05:02

    Check out this code, it might be what you're looking for. For example, inside the main method if we had:

    System.out.println(convert(22));
    

    Output:

    twenty two
    

    EDIT I've reproduced the code below, cleaning up the formatting a bit (main-method is at the bottom):

    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", " ");
        }
    
        public static void main(String[] args) {
            System.out.println(convert(22));  // "twenty two"
        }
    }
    
    0 讨论(0)
  • 2020-12-07 05:08

    While the accepted answer works, it would probably be best to use already-implemented functions to perform this. ICU4J contains a class com.ibm.icu.text.RuleBasedNumberFormat that can be used to perform this operation. It also supports languages other than English, and the reverse operation, parsing a text string to integer values.

    Here is an example, assuming that we have the ICU4J dependency in the classpath:

    import com.ibm.icu.text.RuleBasedNumberFormat;
    import java.util.Locale;
    
    RuleBasedNumberFormat nf = new RuleBasedNumberFormat (Locale.UK, RuleBasedNumberFormat.SPELLOUT);
    nf.format(24);
    // The result is "twenty-four"
    
    0 讨论(0)
  • 2020-12-07 05:14

    I have a very simple solution that can convert whole integer range in java to hinglish notation

        String h1[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
                    "Seven", "Eight", "Nine", "Ten", "Eleven", "Tweleve", "Thirteen",
                    "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                    "Nineteen" };
            String h2[] = { "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy",
                    "Eighty", "Ninety" };
            String h3[] = { "Hundred", "Thousand", "Lakh", "Crore", "Arab" };
    
    public String parseToHinglishNotation(int num) {
            String word = "";
    
            if (num < 0) {
                word += "Minus ";
                num = -num;
            }
    
            if (num < 20) {
                word += h1[num];
            } else if (num < 100) {
                int temp = num / 10 - 2;
                word += h2[temp];
    
                temp = num % 10;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            } else if (num < 1000) {
                int temp = num / 100;
                word += parseToHinglishNotation(temp) + " " + h3[0];
    
                temp = num % 100;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            } else if (num < 100000) {
                int temp = num / 1000;
                word += parseToHinglishNotation(temp) + " " + h3[1];
    
                temp = num % 1000;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            } else if (num < 10000000) {
                int temp = num / 100000;
                word += parseToHinglishNotation(temp) + " " + h3[2];
    
                temp = num % 100000;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            } else if (num < 1000000000) {
                int temp = num / 10000000;
                word += parseToHinglishNotation(temp) + " " + h3[3];
    
                temp = num % 10000000;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            } else if (num <= 2147483647) {
                int temp = num / 1000000000;
                word += parseToHinglishNotation(temp) + " " + h3[4];
    
                temp = num % 1000000000;
                if (temp > 0) {
                    word += " " + parseToHinglishNotation(temp);
                }
            }
    
            return word;
        }
    
    0 讨论(0)
  • 2020-12-07 05:16

    I know this post is kind of old, but I recently came up with my own solution and figured it might be worth sharing. The primary function numToWords takes any Integer between 1 and 9999 (inclusive) and outputs its corresponding English words, followed by the String of digits in parenthesis.

    Example: If Integer x = 2614;, numToText(x); returns "Two Thousand Six Hundred Fourteen (2614)":

    The digit-equivalent words are stored in HashMaps depending on whether they're multiples of 1 or 10 (e.g. 6 --> "Six", 60 --> "Sixty") while the teens are handled independently with a switch statement.

    import java.util.HashMap;
    
    public class Converter{
    
        public Converter(){
            hm1.put(0, "");
            hm1.put(1, "One");
            hm1.put(2, "Two");
            hm1.put(3, "Three");
            hm1.put(4, "Four");
            hm1.put(5, "Five");
            hm1.put(6, "Six");
            hm1.put(7, "Seven");
            hm1.put(8, "Eight");
            hm1.put(9, "Nine");
    
            hm10.put(0, "");
            hm10.put(1, "");
            hm10.put(2, "Twenty ");
            hm10.put(3, "Thirty ");
            hm10.put(4, "Fourty ");
            hm10.put(5, "Fifty ");
            hm10.put(6, "Sixty ");
            hm10.put(7, "Seventy ");
            hm10.put(8, "Eighty ");
            hm10.put(9, "Ninety ");
        }
    
        public static String numToWords(Integer x){
                // Obtain a char[] of the Integer to analyze each digit.
            String s = x.toString();
            char[] cArray = s.toCharArray();
    
                // Refer to the length of the Integer as its final index.
            int l = cArray.length-1;
            String retStr = "";
                // The loop counts backwards from the right-most digit. 
            for(int i = l; i >= 0; i--){
                    // Determine the numeric value at the left-most index, then move rightward.
                    // This setup is attributed to the nuances of the English language.
                int j = Character.getNumericValue(cArray[l-i]);
                    //
                if(i == 3){
                    retStr += hm1.get(j);
                    retStr += " Thousand ";
                } else if(i == 2){
                    retStr += hm1.get(j);
                    retStr += " Hundred ";    
                } else if(i == 1){
                        //If the 10s digit is 1, the final word is 10 <= x <= 19.
                    if(j == 1){
                        String tens = "";
                            // Check the 1s digit to determine x (10 <= x <= 19)
                        switch(Character.getNumericValue(cArray[l])){
                            case 0: tens = "Ten";                   
                                    break;  
                            case 1: tens = "Eleven";                    
                                    break;
                            case 2: tens = "Twelve";
                                    break;
                            case 3: tens = "Thirteen";
                                    break;
                            case 4: tens = "Fourteen";
                                    break;
                            case 5: tens = "Fifteen";
                                    break;
                            case 6: tens = "Sixteen";
                                    break;
                            case 7: tens = "Seventeen";
                                    break;
                            case 8: tens = "Eighteen";
                                    break;
                            case 9: tens = "Nineteen";
                                    break;
                            }
                        i = -1; // Ensure it's the last word by indexing out of the loop.
                        retStr += tens;
                    } else {
                            //If the 10s digit is 2 <= x <= 9, the 10s word is 20 <= x <= 90.
                        retStr += hm10.get(j);
                    }
                } else if(i == 0){
                    retStr += hm1.get(j);
                }
            }
            return retStr + " (" + x + ") ";
        }
    
        private HashMap<Integer, String> hm1 = new HashMap<Integer, String>();
        private HashMap<Integer, String> hm10 = new HashMap<Integer, String>();
    }
    
    0 讨论(0)
提交回复
热议问题