Example of using String.format() with a number / does this function even work?

Per the docs

format(String, List<String>)

Treat the current string as a pattern that should be used for substitution in the same manner as apex:outputText.

Which would lead me to think this would be a great function

public static String toCurrencyString(Decimal input) {
    return String.format('{0,number,currency}', new String[] { input.format());

But that just throws a System.StringException: Cannot format given Object as a Number

Is there anyway to use this function for more than just basic string substitution? Or should I just consider this apparent platform bug one of those special Salesforce “features” that will never get fixed.


String.format() seems to accept only Strings as arguments, it’s less powerful than apex:outputText.

Check the @Abhinav‘s blog post at http://www.tgerm.com/2011/01/message-format-string-format-apex.html, vote for his idea

I think for now your best choice is this:

Decimal x = 123456789.01;

It outputs 123,456,789.01 in my current en_GB locale. Different locales (like de) can have dots and commas swapped around.

Source : Link , Question Author : Ralph Callaway , Answer Author : Community

Leave a Comment