How to convert a number into a formatted string?

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 });

Answer

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);

Attribution
Source : Link , Question Author : Ralph Callaway , Answer Author : John Watson

Leave a Comment