Converting a number to english word in java

You can use the below java class to convert a number to english word,

/*
* Number to English word converter
*/
package com.tms.utility;

/**
*
* @author aarnav
*/
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 EnglishNumberToWords() {}

private static String convertLessThanOneThousand(int number) {
String intialNum;

if (number % 100 < 20){
intialNum = numNames[number % 100];
number /= 100;
}
else {
intialNum = numNames[number % 10];
number /= 10;

intialNum = tensNames[number % 10] + intialNum;
number /= 10;
}
if (number == 0) return intialNum;
return numNames[number] + " hundred" + intialNum;
}

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

String snumber = Long.toString(number);

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

int billions = Integer.parseInt(snumber.substring(0,3));

int millions = Integer.parseInt(snumber.substring(3,6));

int hundredThousands = Integer.parseInt(snumber.substring(6,9));

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;

// removing extra spaces
return result.replaceAll("^\s+", "").replaceAll("\b\s{2,}\b", " ");
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *