How to convert number to words in java

Viewed 400843

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. But we are running into issues for numbers which are huge.

10183 = Ten thousand one hundred eighty three
90 = Ninety
5888 = Five thousand eight hundred eighty eight

Is there an easy to use function in any of the math libraries which I can use for this purpose?

31 Answers
package it.tommasoresti.facebook;

class NumbersToWords {

    private static final String ZERO = "zero";
    private static String[] oneToNine = {
            "one", "two", "three", "four", "five", "six", "seven", "eight", "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 eight hundred ninety"));
}

You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.

POM Entry

     <dependency>
        <groupId>com.ibm.icu</groupId>
        <artifactId>icu4j</artifactId>
        <version>64.2</version>
    </dependency>

Code is

public class TranslateNumberToWord {

/**
 * Translate
 * 
 * @param ctryCd
 * @param lang
 * @param reqStr
 * @param fractionUnitName
 * @return
 */
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
    StringBuffer result = new StringBuffer();

    Locale locale = new Locale(lang, ctryCd);
    Currency crncy = Currency.getInstance(locale);

    String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
    RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

    int i = 0;
    for (String input : inputArr) {
        CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
        if (i++ == 0) {
            result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
        } else {
            result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
        }
    }
    return result.toString();
}

public static void main(String[] args) {
    String ctryCd = "US";
    String lang = "en";
    String input = "95.17";

    String result = translate(ctryCd, lang, input, "Cents");
    System.out.println("Input: " + input + " result: " + result);
}}

Tested with quite a big number and output would be

Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents 

Here is a very simple class NumberInWords.java that can have the job done very easily:

String numberInWords = NumberInWords.convertNumberToWords(27546); //twenty seven thousand and five hundred forty six

It's important to know that this class is only capable of converting int datatype.

The same accepted answer (Jigar Joshi), but now in Spanish. Feel free to change this if you find a mistake. Easier than french, but based on that though....

Spanish:

import java.text.*;

class SpanishNumberToWords {
  private static final String[] tensNames = {
    "",
    "",
    "veinte",
    "treinta",
    "cuarenta",
    "cincuenta",
    "sesenta",
    "setenta",
    "ochenta",
    "noventa"
  };

  private static final String[] unitNames1 = {
    "",
    "un",
    "dos",
    "tres",
    "cuatro",
    "cinco",
    "seis",
    "siete",
    "ocho",
    "nueve",
    "diez",
    "once",
    "doce",
    "trece",
    "catorce",
    "quince",
    "dieciseis",
    "diecisiete",
    "dieciocho",
    "diecinueve",
    "veinte",
    "veintiun",
    "veintidos",
    "veintitres",
    "veinticuatro",
    "veinticinco",
    "veintiseis",
    "veintisiete",
    "veintiocho",
    "veintinueve",
  };

  private static final String[] unitNames2 = {
    "",
    "",
    "dosc",
    "tresc",
    "cuatroc",
    "quin",
    "seisc",
    "setec",
    "ochoc",
    "novec",
    "diez"
  };

  private SpanishNumberToWords() {}

  private static String convertZeroToHundred(int number) {

    int theTens = number / 10;
    int theUnit = number % 10;
    String result = "";

    // separator
    String theSeparator = "";
    if (theTens > 1) {
        theSeparator = " y ";
    }
    // particular cases
    switch (theUnit) {
    case 0:
        theSeparator = "";
      break;
    default:
    }

    // tens in letters
    switch (theTens) {
    case 0:
        result = unitNames1[theUnit];
      break;
    case 1: case 2:
        result =  unitNames1[theTens*10+theUnit];
        break;
    default :
        result = tensNames[theTens]
                              + theSeparator + unitNames1[theUnit];
    }
    return result;
  }

  private static String convertLessThanOneThousand(int number) {

    int theHundreds = number / 100;
    int leReste = number % 100;
    String sReste = convertZeroToHundred(leReste);

    String result;
    switch (theHundreds) {
    case 0:
        result = sReste;
      break;
    case 1 :
      if (leReste > 0) {
          result = "ciento " + sReste;
      }
      else {
          result = "cien";
      }
      break;
    default :
      if (leReste > 0) {
          result = unitNames2[theHundreds] + "ientos " + sReste;
      }
      else {
          result = unitNames2[theHundreds] + "ientos";
      }
    }
    return result;
  }

  public static String convert(long number) {
    // 0 à 999 999 999 999
    if (number == 0) { return "cero"; }

    String snumber = Long.toString(number);

    // pad des "0"
    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    snumber = df.format(number);

    // XXXnnnnnnnnn
    int theMilliards = Integer.parseInt(snumber.substring(0,3));
    // nnnXXXnnnnnn
    int theMillions  = Integer.parseInt(snumber.substring(3,6));
    // nnnnnnXXXnnn
    int theCentMiles = Integer.parseInt(snumber.substring(6,9));
    // nnnnnnnnnXXX
    int lesMille = Integer.parseInt(snumber.substring(9,12));

    String tradMilliards;
    switch (theMilliards) {
    case 0:
      tradMilliards = "";
      break;
    case 1 :
      tradMilliards = convertLessThanOneThousand(theMilliards)
         + " mil millones ";
      break;
    default :
      tradMilliards = convertLessThanOneThousand(theMilliards)
         + " mil millones ";
    }
    String resultat =  tradMilliards;

    String tradMillions;
    switch (theMillions) {
    case 0:
      tradMillions = "";
      break;
    case 1 :
      tradMillions = convertLessThanOneThousand(theMillions)
         + " millon ";
      break;
    default :
      tradMillions = convertLessThanOneThousand(theMillions)
         + " millones ";
    }
    resultat =  resultat + tradMillions;

    String tradCentMille;
    switch (theCentMiles) {
    case 0:
      tradCentMille = "";
      break;
    case 1 :
      tradCentMille = "mil ";
      break;
    default :
      tradCentMille = convertLessThanOneThousand(theCentMiles)
         + " mil ";
    }
    resultat =  resultat + tradCentMille;

    String tradMille;
    tradMille = convertLessThanOneThousand(lesMille);
    resultat =  resultat + tradMille;

    return resultat;
  }

  public static void main(String[] args) {
    System.out.println("*** " + SpanishNumberToWords.convert(0));
    System.out.println("*** " + SpanishNumberToWords.convert(1));
    System.out.println("*** " + SpanishNumberToWords.convert(2));
    System.out.println("*** " + SpanishNumberToWords.convert(3));
    System.out.println("*** " + SpanishNumberToWords.convert(4));
    System.out.println("*** " + SpanishNumberToWords.convert(5));
    System.out.println("*** " + SpanishNumberToWords.convert(7));
    System.out.println("*** " + SpanishNumberToWords.convert(12));
    System.out.println("*** " + SpanishNumberToWords.convert(16));
    System.out.println("*** " + SpanishNumberToWords.convert(19));
    System.out.println("*** " + SpanishNumberToWords.convert(21));
    System.out.println("*** " + SpanishNumberToWords.convert(24));
    System.out.println("*** " + SpanishNumberToWords.convert(28));
    System.out.println("*** " + SpanishNumberToWords.convert(29));
    System.out.println("*** " + SpanishNumberToWords.convert(30));
    System.out.println("*** " + SpanishNumberToWords.convert(31));
    System.out.println("*** " + SpanishNumberToWords.convert(42));
    System.out.println("*** " + SpanishNumberToWords.convert(71));
    System.out.println("*** " + SpanishNumberToWords.convert(72));
    System.out.println("*** " + SpanishNumberToWords.convert(80));
    System.out.println("*** " + SpanishNumberToWords.convert(81));
    System.out.println("*** " + SpanishNumberToWords.convert(89));
    System.out.println("*** " + SpanishNumberToWords.convert(90));
    System.out.println("*** " + SpanishNumberToWords.convert(91));
    System.out.println("*** " + SpanishNumberToWords.convert(97));
    System.out.println("*** " + SpanishNumberToWords.convert(100));
    System.out.println("*** " + SpanishNumberToWords.convert(101));
    System.out.println("*** " + SpanishNumberToWords.convert(110));
    System.out.println("*** " + SpanishNumberToWords.convert(120));
    System.out.println("*** " + SpanishNumberToWords.convert(200));
    System.out.println("*** " + SpanishNumberToWords.convert(201));
    System.out.println("*** " + SpanishNumberToWords.convert(232));
    System.out.println("*** " + SpanishNumberToWords.convert(999));
    System.out.println("*** " + SpanishNumberToWords.convert(521));
    System.out.println("*** " + SpanishNumberToWords.convert(912));
    System.out.println("*** " + SpanishNumberToWords.convert(999));
    System.out.println("*** " + SpanishNumberToWords.convert(1000));
    System.out.println("*** " + SpanishNumberToWords.convert(1001));
    System.out.println("*** " + SpanishNumberToWords.convert(10000));
    System.out.println("*** " + SpanishNumberToWords.convert(10001));
    System.out.println("*** " + SpanishNumberToWords.convert(100000));
    System.out.println("*** " + SpanishNumberToWords.convert(267578));
    System.out.println("*** " + SpanishNumberToWords.convert(3000000000L));
    System.out.println("*** " + SpanishNumberToWords.convert(2147483647));
    /*
     *** OUTPUT
        *** cero
        *** un
        *** dos
        *** tres
        *** cuatro
        *** cinco
        *** siete
        *** doce
        *** dieciseis
        *** diecinueve
        *** veintiun
        *** veinticuatro
        *** veintiocho
        *** veintinueve
        *** treinta
        *** treinta y un
        *** cuarenta y dos
        *** setenta y un
        *** setenta y dos
        *** ochenta
        *** ochenta y un
        *** ochenta y nueve
        *** noventa
        *** noventa y un
        *** noventa y siete
        *** cien
        *** ciento un
        *** ciento diez
        *** ciento veinte
        *** doscientos
        *** doscientos un
        *** doscientos treinta y dos
        *** novecientos noventa y nueve
        *** quinientos veintiun
        *** novecientos doce
        *** novecientos noventa y nueve
        *** mil 
        *** mil un
        *** diez mil 
        *** diez mil un
        *** cien mil 
        *** doscientos sesenta y siete mil quinientos setenta y ocho
        *** tres mil millones 
        *** dos mil millones ciento cuarenta y siete millones cuatrocientos ochenta y tres mil seiscientos cuarenta y siete
     */
  }

Intuitive solution

1: Build a sorted matrix of [value - word] type

2: Find the closest value from matrix for which n/value > 0 (can use binary_search)

3: Recursively build the left and the right part of the number.

Your answer is left_part + word + right_part

class Solution {
    private final Object[][] pairs = {
            {1000_000_000, "Billion"}, {100_00_00, "Million"}, {1000, "Thousand"}, {100, "Hundred"},
            {90, "Ninety"}, {80, "Eighty"}, {70, "Seventy"}, {60, "Sixty"},
            {50, "Fifty"}, {40, "Forty"}, {30, "Thirty"}, {20, "Twenty"},
            {19, "Nineteen"}, {18, "Eighteen"}, {17, "Seventeen"}, {16, "Sixteen"},
            {15, "Fifteen"}, {14, "Fourteen"}, {13, "Thirteen"}, {12, "Twelve"},
            {11, "Eleven"}, {10, "Ten"}, {9, "Nine"}, {8, "Eight"},
            {7, "Seven"}, {6, "Six"}, {5, "Five"}, {4, "Four"},
            {3, "Three"}, {2, "Two"}, {1, "One"}
    };

    private Object[] getPair(int num) {
        int n = pairs.length;
        int l = 0, r = n - 1;
        int result = -1;
        while (l <= r) {
            int mid = (l + r) >>> 1;
            int value = (Integer) pairs[mid][0];
            if (value == num) {
                return pairs[mid];
            }
            else if (num / value > 0) {
                result = mid;
                r = mid - 1;
            }
            else {
                l = mid + 1;
            }
        }
        return pairs[result];
    }

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        var pair = getPair(num);
        String word = (String) pair[1];
        int value = (Integer) pair[0];
        var left = num >= 100 ? numberToWords(num / value) + " " : "";
        var right = num % value == 0 ? "" : " " + numberToWords(num % value);
        return left + word + right;
    }
}

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();
        }
    }
}

I tried to make the code more readable. This works for numbers within integer range

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;

public class Solution2 {

    static Map<Integer, String> numberMap = new HashMap<Integer, String>();
    static Map<Integer, String> tensMap = new HashMap<Integer, String>();
    static Map<Integer, String> exponentsMap = new HashMap<Integer, String>();
    
    public static void main(String[] args) {

        LinkedList<String> wordList = new LinkedList<String>();
        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
        scan.close();

        exponentsMap.put(3, "thousand");
        exponentsMap.put(6, "million");
        exponentsMap.put(9, "billion");

        tensMap.put(2, "twenty");
        tensMap.put(3, "thirty");
        tensMap.put(4, "forty");
        tensMap.put(5, "fifty");
        tensMap.put(6, "sixty");
        tensMap.put(7, "seventy");
        tensMap.put(8, "eighty");
        tensMap.put(9, "ninety");

        numberMap.put(1, "one");
        numberMap.put(2, "two");
        numberMap.put(3, "three");
        numberMap.put(4, "four");
        numberMap.put(5, "five");
        numberMap.put(6, "six");
        numberMap.put(7, "seven");
        numberMap.put(8, "eight");
        numberMap.put(9, "nine");
        numberMap.put(10, "ten");
        numberMap.put(11, "eleven");
        numberMap.put(12, "twelve");
        numberMap.put(13, "thirteen");
        numberMap.put(14, "fourteen");
        numberMap.put(15, "fifteen");
        numberMap.put(16, "sixteen");
        numberMap.put(17, "seventeen");
        numberMap.put(18, "eighteen");
        numberMap.put(19, "nineteen");

        int temp = input;
        
        int exponentCounter =0;
        while(temp>0) {
            // words from 1 to 99
            addLastTwo(temp%100,wordList);
            temp=temp/100;
            
            // add hundreds before exponents
            if(temp!=0) {
                wordList.addFirst("hundred");
                wordList.addFirst(numberMap.getOrDefault(temp%10,""));
                temp = temp/10;
            }
            
            // words for exponents
            if(temp!=0) {
                exponentCounter+=3;
                wordList.addFirst(exponentsMap.getOrDefault(exponentCounter,""));
            }
        }
        wordList.stream().filter(word -> !word.contentEquals("")).forEach(word -> System.out.print(word + " "));
    }

    private static void addLastTwo(int num, LinkedList<String> wordList) {
        if (num > 19) {
            wordList.addFirst(numberMap.getOrDefault(num % 10,""));
            wordList.addFirst(tensMap.getOrDefault(num / 10,""));
            
        } else {
            wordList.addFirst(numberMap.getOrDefault(num,""));
        }
    }
}

Find this code for Indian rupees and in lakhs & crores than Million and Billion. You can pass String or Bigdecimal to the method. This will give the correct output for paisa as well.

package yourpackage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Currency {
    
    public static String convertToWords(BigDecimal num) {
        return convertToWords(num.toString());
    }

    public static String convertToWords(String num) {
        BigDecimal bd = new BigDecimal(num);
        long number = bd.longValue();
        long no = bd.longValue();
        int decimal = (int) (bd.remainder(BigDecimal.ONE).doubleValue() * 100);
        int digits_length = String.valueOf(no).length();
        int i = 0;
        ArrayList<String> str = new ArrayList<>();
        HashMap<Integer, String> words = new HashMap<>();
        words.put(0, "");
        words.put(1, "One");
        words.put(2, "Two");
        words.put(3, "Three");
        words.put(4, "Four");
        words.put(5, "Five");
        words.put(6, "Six");
        words.put(7, "Seven");
        words.put(8, "Eight");
        words.put(9, "Nine");
        words.put(10, "Ten");
        words.put(11, "Eleven");
        words.put(12, "Twelve");
        words.put(13, "Thirteen");
        words.put(14, "Fourteen");
        words.put(15, "Fifteen");
        words.put(16, "Sixteen");
        words.put(17, "Seventeen");
        words.put(18, "Eighteen");
        words.put(19, "Nineteen");
        words.put(20, "Twenty");
        words.put(30, "Thirty");
        words.put(40, "Forty");
        words.put(50, "Fifty");
        words.put(60, "Sixty");
        words.put(70, "Seventy");
        words.put(80, "Eighty");
        words.put(90, "Ninety");
        String digits[] = { "", "Hundred", "Thousand", "Lakh", "Crore" };
        while (i < digits_length) {
            int divider = (i == 2) ? 10 : 100;
            number = no % divider;
            no = no / divider;
            i += divider == 10 ? 1 : 2;
            if (number > 0) {
                int counter = str.size();
                String plural = (counter > 0 && number > 9) ? "s" : "";
                String tmp = (number < 21) ? words.get(Integer.valueOf((int) number)) + " " + digits[counter] + plural
                        : words.get(Integer.valueOf((int) Math.floor(number / 10) * 10)) + " "
                                + words.get(Integer.valueOf((int) (number % 10))) + " " + digits[counter] + plural;
                str.add(tmp);
            } else {
                str.add("");
            }
        }

        Collections.reverse(str);
        String Rupees = String.join(" ", str).trim();

        String paise = (decimal) > 0
                ? " And " + words.get(Integer.valueOf((int) (decimal - decimal % 10))) + " "
                        + words.get(Integer.valueOf((int) (decimal % 10))) + " Paise "
                : "";
        return "Rupees " + Rupees + paise + " Only";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("56721351 = " + Currency.convertToWords(new BigDecimal(56721351)));
        System.out.println("76521351.61 = " + Currency.convertToWords("76521351.61"));
    }

}

When you run this program for 56721351(as Bigdecimal) and 76521351.61(as String) the output is

56721351 = Rupees Five Crore Sixty Seven Lakhs Twenty One Thousands Three Hundred Fifty One Only
76521351.61 = Rupees Seven Crore Sixty Five Lakhs Twenty One Thousands Three Hundred Fifty One And Sixty One Paise  Only

Below java program demonstrate how to convert a number from zero to one million.

NumberToStringLiteral class :

public class NumberToStringLiteral
{

    public static void main(String[] args)
    {
        NumberToStringLiteral numberToStringLiteral = new NumberToStringLiteral();
        int number = 123456;
        String stringLiteral = numberToStringLiteral.convertIntegerToStringLiteral(number);
        System.out.println(stringLiteral);
    }
    
    private String convertIntegerToStringLiteral(int number)
    {
        if (number < 100)
            return from_0_To_100(number);
        
        if ( number >= 100 && number < 1000 )
            return from_101_To_999(number);
        
        if ( number >= 1000 && number <= 99999)
            return from_1000_To_99999(number);
        
        if (number <= 1000000)
            return from_100000_and_above(number);
        
        return Digits.OVER_ONE_MILLION.getStringLiteral();
    }
    
    private String from_0_To_100(int number)
    {
        if (number <= 19 )
            return ZeroToNineteen.getStringLiteral(number);
        
        String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 10) != ZeroToNineteen.ZERO.getStringLiteral() ) ? 
                            ZeroToNineteen.getStringLiteral(number % 10) : "";
        return Tens.getStringLiteralFromNumber( (number - (number % 10 )) ) + " " + LastDigit;
    }
    
    private String from_101_To_999(int number)
    {
        String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 100) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
                            ZeroToNineteen.getStringLiteral(number % 100)  : "";
        
        if ( (number % 100) > 19)
            LastDigit = from_0_To_100(number % 100);
            
        if (LastDigit.isBlank())
            return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(0));
            
        return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
    }
        
    private String from_1000_To_99999(int number)
    {
        String LastDigit = (number % 1000 < 20 ) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
        
        if (LastDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.getStringLiteral()))
            LastDigit = "";
        
        return from_0_To_100(number / 1000 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
    }
    
    private String from_100000_and_above(int number)
    {
        if (number == 1000000)
            return Digits.ONE_MILLION.getStringLiteral();
        
        String lastThreeDigit = (number % 1000 <= 100)  ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
        
        if (lastThreeDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.toString()))
            lastThreeDigit = "";
        
        String number1 = from_101_To_999(number / 1000) + Digits.THOUSAND.getStringLiteral() +  lastThreeDigit;
        return String.valueOf(number1);
    }
    
    private int getNumberOfDigit(int number)
    {
        int count = 0;
        while ( number != 0 )
        {
            number /=  10;
            count++;
        }
        return count;
    }
}

ZeroToNineteen enum :

public enum ZeroToNineteen
{
    ZERO(0, "zero"), 
    ONE(1, "one"),
    TWO(2, "two"),
    THREE(3, "three"),
    FOUR(4, "four"),
    FIVE(5, "five"),
    SIX(6, "six"),
    SEVEN(7, "seven"),
    EIGHT(8, "eight"),
    NINE(9, "nine"),
    TEN(10, "ten"),
    ELEVEN(11, "eleven"),
    TWELVE(12, "twelve"),
    THIRTEEN(13, "thirteen"),
    FOURTEEN(14, "fourteen"),
    FIFTEEN(15, "fifteen"),
    SIXTEEN(16, "sixteen"),
    SEVENTEEN(17, "seventeen"),
    EIGHTEEN(18, "eighteen"),
    NINETEEN(19, "nineteen");
    
    
    private int number;
    private String stringLiteral;
    public static Map<Integer, String> stringLiteralMap;
    
    ZeroToNineteen(int number, String stringLiteral)
    {
        this.number = number;
        this.stringLiteral = stringLiteral;
    }
    
    public int getNumber()
    {
        return this.number;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteral(int number)
    {
        if (stringLiteralMap == null)
            addData();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addData()
    {
        stringLiteralMap = new HashMap<>();
        for (ZeroToNineteen zeroToNineteen : ZeroToNineteen.values())
        {
            stringLiteralMap.put(zeroToNineteen.getNumber(), zeroToNineteen.getStringLiteral());
        }
    }
}

Tens enum :

public enum Tens
{
    TEN(10, "ten"),
    TWENTY(20, "twenty"),
    THIRTY(30, "thirty"),
    FORTY(40, "forty"),
    FIFTY(50, "fifty"),
    SIXTY(60, "sixty"),
    SEVENTY(70, "seventy"),
    EIGHTY(80, "eighty"),
    NINETY(90, "ninety"),
    HUNDRED(100, "one hundred");
    
    
    private int number;
    private String stringLiteral;
    private static Map<Integer, String> stringLiteralMap;
    
    Tens(int number, String stringLiteral)
    {
        this.number = number;
        this.stringLiteral = stringLiteral;
    }
    
    public int getNumber()
    {
        return this.number;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteralFromNumber(int number)
    {
        if (stringLiteralMap == null)
            addDataToStringLiteralMap();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addDataToStringLiteralMap()
    {
        stringLiteralMap = new HashMap<Integer, String>();
        for (Tens tens : Tens.values())
            stringLiteralMap.put(tens.getNumber(), tens.getStringLiteral());
    }
}

Digits enum :

public enum Digits
{
    HUNDRED(3, " hundred and "),
    THOUSAND(4, " thousand "),
    TEN_THOUSAND(5," thousand "),
    ONLY_HUNDRED(0, " hundred" ),
    ONE_MILLION(1000000, "one million"),
    OVER_ONE_MILLION(1000001, "over one million");
    
    private int digit;
    private String stringLiteral;
    private static Map<Integer, String> stringLiteralMap;
    
    private Digits(int digit, String stringLiteral)
    {
        this.digit = digit;
        this.stringLiteral = stringLiteral;
    }
    
    public int getDigit()
    {
        return this.digit;
    }
    
    public String getStringLiteral()
    {
        return this.stringLiteral;
    }
    
    public static String getStringLiteral(int number)
    {
        if ( stringLiteralMap == null )
            addStringLiteralMap();
        
        return stringLiteralMap.get(number);
    }
    
    private static void addStringLiteralMap()
    {
        stringLiteralMap = new HashMap<Integer, String>();
        for ( Digits digits : Digits.values() )
            stringLiteralMap.put(digits.getDigit(), digits.getStringLiteral());
    }
}

Output :

one hundred and twenty three thousand four hundred and fifty six

Note: I have used all three enum for constant variables, you can also use array.

Hope this will help you, Let me know if you have any doubt in comment section.

Related