Salesforce Apex: Data Formatting

We have a blog explaining how to format the data in Visualforce Page. However, sometimes, we prefer to do this in Apex class instead. This gives us more control over the formatted data, e.g, reuse the formatted data to concatenate with the other data. Below is the example of formatting in Apex class:

Formatting DateTime

Datetime myDT =;
//this will give us the time in 24 hours format, e.g, 16:50 01/Jan/2013
String myDate = myDT.format('HH:mm dd/MM/yyyy');

//this will give us the time in 12 hours format, e.g, 04:50 01/Jan/2013
String myDate2 = myDT.format('hh:mm dd/MM/yyyy');

Formatting Currency/Number

Decimal myDecimal = 5000000.555;

//this will give us the number with comma, e.g, 5,000,000.555
String decimalStr = myDecimal.format();

//this will give us the number with 2 decimal points, e.g, 5000000.56
String decimalStrWithScale = myDecimal.setScale(2);

// this will give us the number with comma formatted and 2 decimal points, e.g, 5,000,000.56
String decimalStrWithScaleFormat = myDecimal.setScale(2).format();

//this will give us the number formatted as above but with additional $ sign, e.g, $5,000,000.56
String decimalStrWithDollarSign = string.format('${0}', new string[]{decimalStrWithScaleFormat});