Friday, 15 November 2013

Number to word converter

Visualforce code :



<apex:page controller="Numbertowordclass">
  <apex:form >
  <apex:pageBlock id="pb" >
  <apex:panelGrid columns="2">
   Enter Number:<apex:inputText value="{!num}" size="60"/>
   Enter word:<apex:inputText value="{!wrd}" size="60"/> 
  </apex:panelGrid>
  <apex:pageBlockButtons >
  <apex:commandButton value="Convert" action="{!convert}" reRender="pb"/>
  <apex:commandButton value="Cancel" action="{!Cancel}" reRender="pb"/>
  </apex:pageBlockButtons>
  </apex:pageBlock>
  </apex:form>
</apex:page>


Apex  code :


//This Class will support upto 12 digits :-

public with sharing class Numbertowordclass {

    public void Refresh(){
    num= null;
    wrd= null;
    }

    public PageReference Cancel() {
        Refresh();
        return null;
    }


    public string wrd{set;get;}
    public long num { get; set; }
  
    public string convert() {
      wrd=convert(num);
      return null;
    }
    public String[] units = new String[]{'Zero ','One ','Two ','Three ','Four ','Five ','Six ','Seven ','Eight ','Nine
        ','Ten ', 'Eleven ','Twelve ','Thirteen ','Fourteen ','Fifteen ', 'Sixteen ','Seventeen ','Eighteen ',
        'Nineteen '};
    public String[] tens = new String[]{'','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'};
 
    //This method is used to convert the integer to words
    public  String convert(long i) {
      //
      if( i < 20)  return units[integer.valueOf(i)];
      if( i < 100) return tens[integer.valueOf(i)/10] + ((math.mod(i , 10) > 0)? '' + convert(math.mod(i , 
         10)):'');
      if( i < 1000) return units[integer.valueOf(i)/100] + ' Hundred ' + ((math.mod(i , 100) > 0)?' ' + 
        convert(math.mod(i , 100)):'');
      if( i < 10000) return units[integer.valueOf(i)/1000] + ' Thousand ' + ((math.mod(i , 1000) > 0)?' ' + 
        convert(math.mod(i , 1000)):'');
      if( i < 1000000) return convert(i / 1000) + ' Thousand ' + ((math.mod(i , 1000) > 0)? '' +  
         convert(math.mod(i ,1000)):'') ;
      if(i < 100000000) return convert(i / 1000000) + ' Milion ' + ((math.mod(i , 1000000) > 0)? '' + 
        convert(math.mod(i , 1000000)):'') ;
      if(i < 1000000000) return convert(i / 1000000) + 'Milion ' + ((math.mod(i , 1000000) > 0)? '' + 
        convert(math.mod(i , 1000000)):'') ;    
      return convert(i / 1000000000) + ' Bilian ' + ((math.mod(i , 1000000000) > 0)? '' + 
        convert(math.mod(i , 1000000000)):'') ;
}
}
 


No comments:

Post a Comment