Activity Forums Salesforce® Discussions What is a concise function that formats a (String) decimal into a currency format in Salesforce Apex?

  • What is a concise function that formats a (String) decimal into a currency format in Salesforce Apex?

  • Manpreet

    Member
    May 2, 2017 at 1:37 pm

    What is a concise function that formats a (String) decimal into a currency format in Apex?

  • Saurabh

    Member
    May 2, 2017 at 2:52 pm

    Hi Manpreet

    public static String currency(String i) {
    String s = ( Decimal.valueOf(i==null||i.trim()==''?'0':i).setScale(2) + 0.001 ).format();
    return s.substring(0,s.length()-1);
    }

    Hope it may help

  • Parul

    Member
    September 28, 2018 at 7:24 pm

    Currency format of different countries are different,so we assume here “1,000.00” as currency format because in most of English countries this currency format is used.Let’s try this code-

    String i=’2050066.50′;
    String s = ( Decimal.valueOf(i==null||i.trim()==”?’0′:i).setScale(2) + 0.001 ).format();
    String p = s.substring(0,s.length()-1);
    System.debug(p);

     

    Thanks

  • Avnish Yadav

    Member
    September 30, 2018 at 5:12 am

    The following should do the trick, with the assumption that your locale for currency formatting is correct. Edited to handle null being passed, and zero values after the decimal.
    `
    public static String currency(String input) {
    if ( input == null ) {
    return '0.00';
    }

    Decimal d1 = Decimal.valueOf(input).setScale(2);
    String str = d1.format();
    if( !str.contains('.' ) ) {
    str = str + '.00';
    }

    return str;
    }
    `
    Thanks.

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos