Tuesday 2 February 2016

Convert Currency Into Words In Salesforce

                       Hi folks. Whenever we go to bank for deposit we have to fill the chellan with amount and address details. So there you can see the field called "Amount In Words". On the hand we can just write the amounts in words simply but how we can do it in salesforce object field?. So I come up with idea to implement this functionality in salesforce. To implement this functionality we need two things,

  1. Apex Class
  2. Apex Trigger
By using apex class and apex triggers we can achieve this functionality. Check the below image to see how it will give an output before implementing.

Currency Into Words in salesforce


Object            : Opportunity
Field               : Amount
Custom Field : Amount_in_Words__c (create this field before going coding)

So we are going to create an apex class and we will call this class into apex trigger.


  public with sharing class ConvertCurrencyToWords {
     
        static String[] to_19 = new string[]{ 'zero', 'One',  'Two', 'Three', 'Four',  'Five',  'Six', 'Seven',
                                              'Eight', 'Nine', 'Ten',  'Eleven', 'Twelve', 'Thirteen',  
                                              'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen' };
        static String[] tens = new string[]{ 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'};
     
        static string[] denom = new string[]{ '',
                                             'Thousand',   'Million',     'Billion',    'trillion',    'quadrillion',  
                                             'quintillion', 's!xtillion',   'septillion',  'octillion',   'nonillion',  
                                             'decillion',  'undecillion',   'duodecillion', 'tredecillion',  'quattuordecillion',  
                                             's!xdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion' };
    // convert a value < 100 to English.  
   public static string convert_nn(integer val) {
             if (val < 20)
        return to_19[val];
      if (val == 100)
          return 'One Hundred';
      for (integer v = 0; v < tens.size(); v++) {
        String dcap = tens[v];
        integer dval = 20 + 10 * v;
        if (dval + 10 > val) {
          if (Math.Mod(val,10) != 0)
            return dcap + ' ' + to_19[Math.Mod(val,10)];
          return dcap;
        }    
      }
      return 'Should never get here, less than 100 failure';
    }
    // convert a value < 1000 to english, special cased because it is the level that kicks   
    // off the < 100 special case. The rest are more general. This also allows you to  
    // get strings in the form of "forty-five hundred" if called directly.  
    public static String convert_nnn(integer val) {
      string word = '';
      integer rem = val / 100;
      integer mod = Math.mod(val,100);
      if (rem > 0) {
        word = to_19[rem] + ' Hundred and';
        if (mod > 0) {
          word += ' ';
        }
      }
      if (mod > 0) {
        word += convert_nn(mod);
      }
      return word;
    }
    public static String english_number(long val) {
      if (val < 100) {
        return convert_nn(val.intValue());
      }
      if (val < 1000) {
        return convert_nnn(val.intValue());
      }
      for (integer v = 0; v < denom.size(); v++) {
        integer didx = v - 1;
        integer dval = (integer)Math.pow(1000, v);
        if (dval > val) {
          integer mod = (integer)Math.pow(1000, didx);
          integer l = (integer) val / mod;
          integer r = (integer) val - (l * mod);
          String ret = convert_nnn(l) + ' ' + denom[didx];
          if (r > 0) {
            ret += ', ' + english_number(r);
          }
          return ret;
        }
      }
      return 'Should never get here, bottomed out in english_number';
    }
  }


Trigger


trigger ConvertCurrencyToWords on Opportunity (before insert, before update) {

    for (Opportunity c : Trigger.new) {
        if (c.Amount != null && c.Amount >= 0) {
         
            Long n = c.Amount.longValue();
            string amo = ConvertCurrencyToWords.english_number(n);
            string amo1 = amo.remove(',');
            c.Amount_in_Words__c = amo1;
        } else {
            c.Amount_in_Words__c = null;
        }
    }
}


Now goto opportunity -> edit or create a record -> enter value for amount field->click on save->now you can see that amount in words at amount_in_words__c field.

Currency Into Words in salesforce

Hope it helps you. If you have any query comment below. Thanks!!.


48 comments:

  1. Thanks Azar bhai.... code is great!!!!!

    ReplyDelete
    Replies
    1. This seems to work for numbers below the billions, but once you get to the billions you start to get to "Should never get here, bottomed out in english_number" likely because Integers are used which have a maximum size of 2,147,483,647 -- I've converted this to utilize Longs wherever possible instead of Integers, and it now works properly.

      Delete
  2. Thanks! This code worked great! But it doesn't include the cents currency after the decimal. Do you have a way to include the cents to the apex class?

    ReplyDelete
    Replies
    1. Hey Madhatter06 do you got chance to include the cents currency after the decimal?.

      Delete
    2. Haven't solved it yet. I created a separate field that cuts the last 2 digits from my currency field, then used your code above again in a separate trigger to convert those decimals to words.

      Formula field #1 "Amount_Cents" trims the decimal from the amount field: TRIM(RIGHT( TEXT(Amount_c) , 2))

      Formula field #2 "Cents_value" converts the field back to currency: Value(Amount_Cents)

      The second trigger then looks at the new currency field.

      The problem is, my formula cutting the decimals doesn't recognize the zero's, so it's not working for any decimal number that end in zero.

      Any suggestions?

      Delete
    3. Add this function to the class:

      public static String convert(Decimal d){
      if(d==null){
      return null;
      }
      String dStr = String.valueOf(d);
      String decimalStr='00';
      if(dStr!=null && dStr.contains('.')){
      decimalStr = dStr.substringAfter('.');
      }
      String retStr = english_number(d.longValue());

      retStr +=' and '+decimalStr+'/100 Dollars';

      return retStr;
      }

      Delete
    4. Fix to above for cents that end in 0 and negative numbers:

      public static String convert(Double d){
      if(d==null){
      return null;
      }
      String negative = '';
      if(d<0){
      d = Math.abs(d);
      negative = 'Negative ';
      }
      System.debug('\n\n------ABS-------\n'+d);
      String dStr = d.format().replaceAll(',','');
      String decimalStr='00';
      if(dStr!=null && dStr.contains('.')){
      decimalStr = dStr.substringAfter('.');
      if(decimalStr.length() == 1){
      decimalStr+= '0';
      }
      }
      String retStr = negative + english_number(d.longValue());

      retStr +=' and '+decimalStr+'/100 Dollars';

      return retStr;
      }

      Delete
  3. Do you have any extension for Decimal places? Thank you.

    ReplyDelete
  4. Superb. Really enjoyed very much with this article here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your updation.
    Android training in chennai

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  5. Thank you so much!! This was really well articulated & easy to follow. May I please have the test class....pls *puppy eyes*

    ReplyDelete
  6. Hi azarudeen,

    Please share your gmail id

    ReplyDelete
  7. can i have it in arabic , i mean to change the number to arabic words

    ReplyDelete
  8. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    ReplyDelete
  9. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
    Best Devops Training in pune
    Devops interview questions and answers

    ReplyDelete
  10. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    python course in pune
    python course in chennai
    python Training in Bangalore

    ReplyDelete
  11. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore

    ReplyDelete
  12. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  13. Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. convert money

    ReplyDelete
  14. Attend The PMP in Bangalore From ExcelR. Practical PMP in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The PMP in Bangalore.
    ExcelR PMP in Bangalore

    ReplyDelete
  15. thank you so much for doing this
    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  16. This post is really creative. Thanks for your efforts in blogging it. Really appreciate it. It has helped me in improving my skill and now i can easily make use of it. Thanks.
    Insightful! This article has a great content.
    Selenium Training in Chennai

    Selenium Training in Velachery

    Selenium Training in Tambaram

    Selenium Training in Porur

    Selenium Training in Omr

    Selenium Training in Annanagar

    ReplyDelete
  17. This blog is very interesting. I learned so much and want to thank you for sharing it in the first place. It is really helpful for my future endeavors. Thanks for your efforts and making it available to public
    Java training in chennai

    python training in chennai

    web designing and development training course in chennai

    selenium training in chennai

    digital-marketing seo training in chennai

    ReplyDelete
  18. what is the test class for this code?

    ReplyDelete
  19. Hi, I have a Amount and In words field and I used this with a trigger, on the Object in Sandbox and its doing Good ( it is getting the value in Words), however I am not able to move to production as its not even 1% coverage. Can you share the Class Test and Trigger Test.

    ReplyDelete

  20. This post is so interactive and informative.keep update more information...
    Java Training in Bangalore
    Java Classes in Pune

    ReplyDelete
  21. If you are looking for Best PMP Training and Certification in Bengaluru? Check and enroll for project management professional course - PMP Training in Bengaluru

    ReplyDelete
  22. Hi,

    I wanted to let you know that this code was a lifesaver! We are a nonprofit and were looking to reduce the time it took to process checks from information created in Salesforce. This will help our staff out significantly and worked perfectly with the triggers and was very simple to convert for USD. Thank you!

    ReplyDelete