Thursday, August 27, 2009

Generic class for Amount in words

package com.evolvus.common.util;

public class AmountInWords {

final static String units[] = {"","one ","two ","three ","four ","five ","six ",
"seven ","eight ","nine ","ten ","eleven ","twelve ","thirteen ",
"fourteen ","fifteen ","sixteen ","seventeen ","eighteen ","nineteen "};
String tens[] = {"", "ten ","twenty ","thirty ","forty ","fifty ","sixty ","seventy ",
"eighty ","ninety "};
public String format(String aHigherCurrency, String aLowerCurrency,
String aAmount, String aSystemCurrencyFormat,int decimalLength) {
String words="";
String[] systemCurrencyFormats = aSystemCurrencyFormat.split(",");
int formatCount = systemCurrencyFormats[0].length();
String higherCurrencyValue = null;
String lowerCurrencyValue = null;
String[] amounts = aAmount.split("\\.");
if (amounts != null && amounts.length > 0) {
higherCurrencyValue = amounts[0];
if (amounts.length > 1)
lowerCurrencyValue = amounts[1];
}
words=words.concat(aHigherCurrency);
words=words.concat(" ");
/* Call to amount to words for higher currency */
words=words.concat(this.intialFormat(Integer.parseInt(higherCurrencyValue), formatCount));
if (lowerCurrencyValue != null) {
if (lowerCurrencyValue.length() > decimalLength) {
lowerCurrencyValue = lowerCurrencyValue.substring(0,
decimalLength);
}
words=words.concat("and ");
/* Call to amount to words for lower currency */
words=words.concat(this.intialFormat(Integer.parseInt(lowerCurrencyValue), 2));
words=words.concat(aLowerCurrency);
}
return words;
}
public String intialFormat(int amount,int foramt)
{
String words = "";
String tword="";
if(foramt==3){
int millions = amount / 1000000;
tword =threeDigits(millions);
if(tword.length()>1)
words=tword + "million ";
amount-= millions*1000000;
}
else if (foramt==2){
int crore = amount / 10000000;
tword =threeDigits(crore);
tword = threeDigits(crore);
if(tword.length()>1)
words+= tword + "crore ";
amount-= crore*10000000;
int lakhs = amount / 100000;
tword = threeDigits(lakhs);
if(tword.length()>1)
words+= tword + "lakh ";
amount-= lakhs*100000;
}
int thousands = amount / 1000;
tword = threeDigits(thousands);
if(tword.length()>1)
words+= tword + "thousand ";
amount-=thousands*1000;
words+=threeDigits(amount);
return words;
}
public String threeDigits(int digits)
{
String digWord = "";
int hnd = digits / 100;
if(hnd>0)
digWord+=units[hnd] + "hundred ";
int ten = digits - hnd *100;
if(ten<20)>
digWord+= units[ten];
else
{
int tenth = ten / 10;
digWord+=tens[tenth];
int last = ten - tenth*10;
digWord+= units[last];
}
return digWord;
}
public static void main(String args[]){
AmountInWords a = new AmountInWords();
/* Inputs
*
* Higher Currency
* Lower Currency
* Amount
* SystemConfiguration
* Selected Currency Decimal Points
* */
String s=a.format("Rupees", "Paisa", "3451234.425", "##,###", 3);
System.out.println(s);
}
}

0 comments:

Post a Comment