Monday, June 15, 2009

Decimal Number convert into words

////..................start Amount to word.........................////
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(Double number) {
// 0 to 999 999 999 999
if (number == 0) {
return "zero";
}

String snumber = Double.toString(number);

// pad with "0"
String mask = "#########.00";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);




// nnnXXXnnnnnn
int crore = Integer.parseInt(snumber.substring(0, 2));
// nnnnnnXXXnnn
int lacks = Integer.parseInt(snumber.substring(2, 4));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(4, 6));
int hundreds = Integer.parseInt(snumber.substring(6, 9));

int paise = Integer.parseInt(snumber.substring(10, 12));

String tradcrores;
switch (crore) {
case 0:
tradcrores = "";
break;
case 1:
tradcrores = convertLessThanOneThousand(crore) + " crore ";
break;
default:
tradcrores = convertLessThanOneThousand(crore) + " crore ";
}


String result = tradcrores;

String tradlacks;

switch (lacks) {
case 0:
tradlacks = "";
break;
case 1:
tradlacks = convertLessThanOneThousand(lacks) + " lacks ";
break;
default:
tradlacks = convertLessThanOneThousand(lacks) + " lacks ";
}
result = result + tradlacks;

String tradThousands;
switch (thousands) {
case 0:
tradThousands = "";
break;
case 1:
tradThousands = "one thousand ";
break;
default:
tradThousands = convertLessThanOneThousand(thousands) + " thousand ";
}

result = result + tradThousands;

String tradHundrads;
tradHundrads = convertLessThanOneThousand(hundreds);
result = result + tradHundrads + " Rupees ";

if (paise > 0) {
String txt_paise = "and " + convertLessThanOneThousand(paise) + " paise Only";

result = result + txt_paise;
} else {
String txt_paise = "and Zero paise Only";

result = result + txt_paise;
}



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

No comments:

Post a Comment