Skip navigation

Monthly Archives: January 2009

Let’s have a break, and have some java.
This time I will create a guide to create a java funtion that will convert numeric to word format.

Example:
We will convert the total number of islands in the Philippines which is 7,107.

Now, lets create a class named NumberWord and declare the constant.

private static final String[] strOnes = {
“”,
” One”,
” Two”,
” Three”,
” Four”,
” Five”,
” Six”,
” Seven”,
” Eight”,
” Nine”,
” Ten”,
” Eleven”,
” Twelve”,
” Thirteen”,
” Fourteen”,
” Fifteen”,
” Sixteen”,
” Seventeen”,
” Eighteen”,
” Nineteen”};

private static final String[] strTens = {
“”,
” Ten”,
” Twenty”,
” Thirty”,
” Forty”,
” Fifty”,
” Sixty”,
” Seventy”,
” Eighty”,
” Ninety”};

For our basic function. We will create the Hundreds function. This function may be call by other function. It will get the modulo of a 3 digit integer and return the number word from the array string strNum and strTens to which ever the modulo falls.

private static String Hundreds(int intNum) {
String strTemp = “”, strHundred = ” Hundred”;

if (intNum % 100 < 20){
strTemp = strOnes[intNum % 100];
intNum /= 100;}
else {
strTemp = strOnes[intNum % 10];
intNum /= 10;

strTemp = strTens[intNum % 10] + strTemp;
intNum /= 10;}
if (intNum == 0) { strHundred = “”; }
strTemp = strOnes[intNum] + strHundred + strTemp;
return strTemp;}

For the thousand and beyond.

public static String convert(int intNumber) {
String strWord=””, strNumber = “”, strCount = “”, strTemp = “”;
int intNum, intLen, intCount = 0;

strNumber = Integer.toString(intNumber);
intLen = strNumber.length();
for(int a=intLen;a>-3;a=a-3){
int x = a-3;
if (a < 3) { x = 0; }
intNum = Integer.parseInt(strNumber.substring(x,a));

strTemp = NumberWord.Hundreds(intNum);

intCount += 1;
switch (intCount){
case 2 : strCount = ” Thounsand”; break;
case 3 : strCount = ” Million”; break;
case 4 : strCount = ” Billion”; break;
case 5 : strCount = ” Trillion”; break;
default : strCount = “”;}
strWord = strTemp + strCount + strWord;
}
return strWord;}

For the Main program, we simply call the method Convert, with an integer parameter.

public static void main(String args[]) {
System.out.println(NumberWord.convert(18));       System.out.println(NumberWord.convert(1234));
}

Advertisements