I don't know of an API for this.
So have this ugly code in one of my projects (which is based on someone else's post that I no longer have a link to):
private static final Map<Integer, Integer> MULTIPLIERS = new Map<Integer, Integer> {
1 => 10,
2 => 100,
3 => 1000,
4 => 10000,
5 => 100000,
6 => 1000000
};
public static String format(Decimal d, Integer places) {
if (d != null) {
// Round first
Decimal dd = d.setScale(places);
// Format to get thousand separators
String w = dd.longValue().format();
if (places != 0) {
if (dd < 0) dd = -dd;
Integer multiplier = MULTIPLIERS.get(places);
// For example 0.0067 becomes 10067 then the leading 1 is dropped to get 0067
String f = String.valueOf(multiplier + Math.mod((dd * multiplier).longValue(), multiplier));
return w + '.' + f.substring(1);
} else {
return w;
}
} else {
return null;
}
}
with test:
@isTest
static void testFormat() {
System.assertEquals(null, StringUtil.format(null, 2));
System.assertEquals('12.34', StringUtil.format(12.34, 2));
System.assertEquals('12.30', StringUtil.format(12.3, 2));
System.assertEquals('12.00', StringUtil.format(12, 2));
// Now rounds; didn't use to
System.assertEquals('12.34', StringUtil.format(12.3444, 2));
System.assertEquals('12.35', StringUtil.format(12.3466, 2));
System.assertEquals('12.34', StringUtil.format(12.344, 2));
System.assertEquals('12.35', StringUtil.format(12.346, 2));
System.assertEquals('12.3400', StringUtil.format(12.34, 4));
System.assertEquals('12.340', StringUtil.format(12.34, 3));
System.assertEquals('12.34', StringUtil.format(12.34, 2));
System.assertEquals('12.3', StringUtil.format(12.34, 1));
System.assertEquals('12', StringUtil.format(12.34, 0));
System.assertEquals('12.00', StringUtil.format(12, 2));
System.assertEquals('12.0', StringUtil.format(12, 1));
System.assertEquals('12', StringUtil.format(12, 0));
System.assertEquals('12.3456', StringUtil.format(12.345644, 4));
System.assertEquals('12.3457', StringUtil.format(12.345666, 4));
System.assertEquals('123,456.12', StringUtil.format(123456.1234, 2));
System.assertEquals('123,456.1235', StringUtil.format(123456.123488, 4));
System.assertEquals('-55,123,456.12', StringUtil.format(-55123456.1234, 2));
System.assertEquals('-123,456.123457', StringUtil.format(-123456.12345678, 6));
System.assertEquals('12', StringUtil.format(12.34, 0));
System.assertEquals('13', StringUtil.format(12.67, 0));
}