12

Note: there is an extensive discussion on converting a string into a decimal. This question asks how to convert a number into a formatted string.

Given a decimal variable, how can I convert that into a formatted string, such as a currency string, i.e. 2000 would become "$2,000.00"? I would have thought this would be an easy task, given the formatting options available in visualforce, e.g. <apex:outputtext value="{0,number,$#,###.##}">, but there doesn't seem to be analagous functionality for apex. Is there a simple method for achieve this?

I first looked at the decimal.format() method, but this doesn't take any parameters. Was hoping for something like this

Decimal input = 2000;
String output = input.format('$#,###.##');

I also looked at the String.format(formatString, inputArray) but you can only use string data types for the input array. Was hoping for something like this

Decimal input = 2000;
String output = String.format('$#,###.##',new Object[] { input });
10
  • 1
    This is discussed at length in this existing SFSE thread: [What is a concise function that formats a (String) decimal into a currency format in Apex?][1] [1]: salesforce.stackexchange.com/questions/318/…
    – greenstork
    Jun 2, 2014 at 23:17
  • @greenstork, I saw that, but it's focused primarily on the reverse case, given a currency string how do I convert it to a decimal. Jun 3, 2014 at 0:18
  • @Bachovski am I missing something or is this not a duplicate? The other question is talking about String -> Decimal, this is the opposite, Decimal -> String. What am I missing? Jun 4, 2014 at 7:44
  • @highfive am I missing something or is this not a duplicate? The other question is talking about String -> Decimal, this is the opposite, Decimal -> String. What am I missing? Jun 4, 2014 at 7:44
  • @Tepsi am I missing something or is this not a duplicate? The other question is talking about String -> Decimal, this is the opposite, Decimal -> String. What am I missing? Jun 4, 2014 at 7:45

4 Answers 4

8

The format method automatically does the commas and periods or visa versa (depending on whether your profile is in the US or elsewhere)

Assuming the $ sign applies to all cases in your org you can simply use

Decimal input = 2000;
String output = '$' + String.valueOf(input.format());

Note the String.valueOf(). This is required because the input variable is defined as a Decimal.

Edit: I noticed a bug with the Decimal.format() method where it will not show any numbers past the decimal point if there are only zeros there, ex. $100.00. To solve this I came up with this method.

private String getCents(Decimal x){
    String y = String.valueOf(x);
    String z = '.';
    if(y.contains(',')) z = ',';
    y = y.substring(0, y.indexOf(z));
    if(x - Decimal.valueOf(y) == 0)
        return String.valueOf(x.format()) + z + '00';
    else return String.valueOf(x.format());
}

Then to update the example above, it would be:

Decimal input = 2000;
String output = '$' + getCents(input);
2
3

This should work, if its until 2 decimals:

Decimal dec;
String amount;
if (!string.valueof(dec.format()).right(3).contains('.')){
    amount = '$' + string.valueof(dec.format()) + '.00';
}else if (string.valueof(dec.format()).right(2).contains('.')){
    amount = '$' + string.valueof(dec.format()) + '0';
}else {
    amount = '$' + string.valueof(dec.format());
}
2

Here is one more version , this one determines the "decimal separator" automatically and adds trailing zeros based on the scale provided.

public static String formatNumberFields(String unformattedValue, Integer scale) {
    String formattedValue = Decimal.valueof(unformattedValue).setScale(scale).format();
    Integer decimalPlaces;
    String decimalSep = 0.23.format().substring(1, 2);

    if(formattedValue.contains(decimalSep)) {
        decimalPlaces = formattedValue.split('\\' + decimalSep)[1].length();
    } else {
        formattedValue += decimalSep;
        decimalPlaces = 0;
    }

    //Add trailing zeros
    while(decimalPlaces < scale) {
        formattedValue += '0';
        decimalPlaces ++;
    }

    return formattedValue;
}
1

i created a class for Utility functions like this.

Here is the code in the Utility class

public static String formatMoney(String s) {
    s = '$' + s;
    if (!s.contains('.')) {
        s = s + '.00';
    } else {
      Integer dPos = s.indexOf('.');
      if (s.length() - dPos < 3) { s = s + '0'; }   
    }
    return s; 
}

Then in my apex class I create a string that will show on my VF Page and call the function

In this particular case the money is coming from a query

String poTotal {get;set;}

poTotal = Utilities.formatMoney(poInfo[0].PO_Amount__c.format());

I can call the Utility function from any apex class and it will format my Decimal value into the string with $1,123.00

But it can be done with anything

String myMoney {get;set;}

public void myFunction() {
  Decimal amt = 1234.1;
  myMoney = Utilities.formatMoney(amt.format());

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .