How to convert number to words in java

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

    This program can convert up to 102 digits long number. Suggestions and comments are highly appreciated.

    package com.kegeesoft;
    /**
     * @author Chandana Gamage +94 710 980 120
     * @author maheshgamage375@gmail.com
     * @author KeGee Software Solutions
     */
    import java.math.BigDecimal;
    import java.math.BigInteger;
    
    public class Converter {
        private final BigInteger zero = new BigInteger("0");        
        private final BigInteger scale[] = new BigInteger[33];                                        
        private final String scaleName[] = {" Duotrigintillion"," Untrigintillion"," Trigintillion",
                                            " Nonvigintillion"," Octovigintillion"," Septvigintillion",
                                            " Sexvigintillion"," Quinvigintillion"," Quattuorvigintillion",
                                            " Trevigintillion"," Duovigintillion"," Unvigintillion",
                                            " Vigintillion"," Novemdecillion"," Octodecillion",
                                            " Septemdecillion"," Sexdecillion"," Quindecillion",
                                            " Quattuordecillion "," Tredecillion"," Duodecillion",
                                            " Undecillion"," Decillion"," Nonillion"," Octillion",
                                            " Septillion"," Sextillion"," Quintillion"," Quadrillion",
                                            " Trillion"," Billion"," Million"," Thousand"};
        private final String ones[] = {""," One"," Two"," Three"," Four"," Five"," Six"," Seven"," Eight"," Nine",
                                       " Ten"," Eleven"," Twelve"," Thirteen"," Fourteen"," Fifteen"," Sixteen",
                                       " Seventeen"," Eighteen"," Nineteen"};    
        private final String tens[] = {"",""," Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"};
        private int index = 0;    
        private String shortValueInWords = "";
        private String output = "";
        private String decimalInWords = "";
        private String valueInWords;
    
        public String setValue(BigInteger value) throws Exception{
            return this.bigValueInWords(value);
        }
    
        public String setValue(BigDecimal value) throws Exception{
            int indexOfDecimalPoint = (value.toString()).indexOf(".");
    
            // Split and pass interger value of given decimal value to constructor
            String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
            BigInteger intValue = new BigInteger(tempIntValue);
    
            // Split and pass decimal value of given decimal value to constructor
            String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
            BigInteger deciValue = new BigInteger(tempDeciValue);
    
            this.bigValueInWords(intValue);
            this.decimalValueInWords(deciValue);
            return null;
        }
    
        public String setValue(BigDecimal value, String currencyName, String centsName) throws Exception{
            int indexOfDecimalPoint = (value.toString()).indexOf(".");
    
            // Split and pass interger value of given decimal value to constructor
            String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
            BigInteger intValue = new BigInteger(tempIntValue);
    
            // Split and pass decimal value of given decimal value to constructor
            String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
            @SuppressWarnings("UnusedAssignment")
            BigInteger deciValue = null;
    
            // Concatenate "0" if decimal value has only single digit
            if(tempDeciValue.length() == 1){
                deciValue = new BigInteger(tempDeciValue.concat("0"));
            }else{
                deciValue = new BigInteger(tempDeciValue);
            }
    
            this.output = currencyName+" ";
            this.bigValueInWords(intValue);
            this.centsValueInWords(deciValue, centsName);
    
            return null;
        }
    
        private String bigValueInWords(BigInteger value) throws Exception{
            // Build scale array
            int exponent = 99;
            for (int i = 0; i < scale.length; i++) {
                scale[i] = new BigInteger("10").pow(exponent);
                exponent = exponent - 3;
            }
    
            /* Idntify whether given value is a minus value or not
                if == yes then pass value without minus sign
                and pass Minus word to output
            */
            if(value.compareTo(zero) == -1){
                value = new BigInteger(value.toString().substring(1,value.toString().length()));
                output += "Minus ";
            }
    
            // Get value in words of big numbers (duotrigintillions to thousands)
            for (int i=0; i < scale.length; i++) {
                if((value.divide(scale[i])).compareTo(zero)==1){
                this.index = (int)(value.divide(scale[i])).intValue();
                output += shortValueInWords(this.index) + scaleName[i];
                value = value.mod(scale[i]);
                }
            }
    
            // Get value in words of short numbers (hundreds, tens and ones)
            output += shortValueInWords((int)(value.intValue()));
    
            // Get rid of any space at the beginning of output and return value in words
            return this.valueInWords = output.replaceFirst("\\s", "");
        }
    
        private String shortValueInWords(int shortValue) throws Exception{
            // Get hundreds
            if(String.valueOf(shortValue).length()==3){
                shortValueInWords = ones[shortValue / 100]+" Hundred"+shortValueInWords(shortValue % 100);
            }
    
            // Get tens
            if(String.valueOf(shortValue).length()== 2 && shortValue >= 20){
                if((shortValue / 10)>=2 && (shortValue % 10)>=0){
                    shortValueInWords = tens[shortValue / 10] + ones[shortValue % 10];
                }
            }
    
            // Get tens between 10 and 20
            if(String.valueOf(shortValue).length()== 2 && shortValue >= 10 && shortValue < 20){
                shortValueInWords = ones[shortValue];
            }
    
            // Get ones
            if(String.valueOf(shortValue).length()==1){
                shortValueInWords = ones[shortValue];
            }
    
            return this.shortValueInWords;
        }
    
        private String decimalValueInWords(BigInteger decimalValue) throws Exception{
            decimalInWords = " Point";
            // Get decimals in point form (0.563 = zero point five six three)
            for(int i=0; i < (decimalValue.toString().length()); i++){
                decimalInWords += ones[Integer.parseInt(String.valueOf(decimalValue.toString().charAt(i)))];
            }
    
            return this.decimalInWords;
        }
    
        private String centsValueInWords(BigInteger decimalValue, String centsName) throws Exception{
            decimalInWords = " and"+" "+centsName;
    
            // Get cents in words (5.52 = five and cents fifty two)
            if(decimalValue.intValue() == 0){
                decimalInWords += shortValueInWords(decimalValue.intValue())+" Zero only";
            }else{
                decimalInWords += shortValueInWords(decimalValue.intValue())+" only";
            }
    
    
            return this.decimalInWords;
        }
    
        public String getValueInWords(){
            return this.valueInWords + decimalInWords;
        }
    
        public static void main(String args[]){
            Converter c1 = new Converter();
            Converter c2 = new Converter();
            Converter c3 = new Converter();
            Converter c4 = new Converter();
    
            try{
                // Get integer value in words
                c1.setValue(new BigInteger("15634886"));
                System.out.println(c1.getValueInWords());
    
                // Get minus integer value in words
                c2.setValue(new BigInteger("-15634886"));
                System.out.println(c2.getValueInWords());
    
                // Get decimal value in words
                c3.setValue(new BigDecimal("358621.56895"));
                System.out.println(c3.getValueInWords());
    
                // Get currency value in words
                c4.setValue(new BigDecimal("358621.56"),"Dollar","Cents");
                System.out.println(c4.getValueInWords());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题