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!!.


62 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. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete
  7. Hi azarudeen,

    Please share your gmail id

    ReplyDelete
  8. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Android App Development Company

    ReplyDelete
  9. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  10. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text
    Mobile Marketing Services
    mobile marketing companies
    Sms API

    ReplyDelete
  11. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

    ReplyDelete
  12. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Mobile Marketing Service
    Mobile Marketing Companies
    Sms API
    Texting API
    sms marketing

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

    ReplyDelete
  14. Excellent read, Positive site, where did u come up with the information on this posting? I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work

    PSD to Wordpress
    wordpress website development

    ReplyDelete
  15. Thanks you for sharing the article. The data that you provided in the blog is infromative and effectve. Through you blog I gained so much knowledge. Also check my collection at Salesforce Online Training Blog

    ReplyDelete
  16. 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
  17. 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
  18. 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
  19. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    python course in pune
    python course in chennai
    python Training in Bangalore

    ReplyDelete
  20. 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
  21. 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
  22. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    AWS Training in Bangalore |Best AWS Training Institute in Bangalore BTM, Marathahalli
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR

    ReplyDelete
  23. 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
  24. I am overwhelmed by your post with such a nice topic. Usually, I visit your blogs and get updated with the information you include but today’s blog would be the most appreciable...

    Thanks
    Cpa offers

    ReplyDelete
  25. I like viewing web sites which comprehend the price of delivering the excellent useful resource Python classes in pune free of charge. I truly adored reading your posting. Thank you!

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

    ReplyDelete
  27. 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
  28. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore / https://www.excelr.com/digital-marketing-training-in-bangalore

    ReplyDelete
  29. 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
  30. I must say you are very skilled at persuasive writing if you can convince me to share your views. I am very impressed by your excellent writing abilities. Please keep up the good informational writing.
    SAP training in Mumbai
    Data Science training in Mumbai
    Best data science training in Mumbai
    SAP training in Mumbai

    ReplyDelete
  31. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  32. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    Artificial Intelligence Training in Chennai

    Ai Training in Chennai

    Artificial Intelligence training in Bangalore

    Ai Training in Bangalore

    Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad

    Artificial Intelligence Online Training

    Ai Online Training

    Blue Prism Training in Chennai

    ReplyDelete
  33. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis. https://www.3ritechnologies.com/course/data-science-online-training/

    ReplyDelete
  34. 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
  35. 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
  36. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    salesforce training in chennai

    software testing training course in chennai

    robotic process automation rpa training in chennai

    blockchain training in chennai

    devops training in chennai

    ReplyDelete
  37. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.salesforce training in chennai

    software testing training in chennai

    robotic process automation rpa training in chennai

    blockchain training in chennai

    devops training in chennai

    ReplyDelete