5

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.

  • 2
    I think String.format accepts only strings... Check tgerm.com/2011/01/message-format-string-format-apex.html ? – eyescream Jun 4 '14 at 8:09
  • Sigh I was afraid of that. Blerg, I hate these holes. Probably expecting too much in hoping they could fix the docs, so at least they don't imply functionality they don't actually have. – Ralph Callaway Jun 4 '14 at 8:18
  • If you wanted to post an answer of "No" and add a link to the idea to vote for the feature, I'd accept it. Stuck waiting for the wait period to answer my own question to expire. – Ralph Callaway Jun 4 '14 at 8:19
  • I was disappointed to find this out myself. I would have thought they'd accept an array of objects. – sfdcfox Jun 4 '14 at 15:07
3

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;
System.debug(x.format());

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

|improve this answer|||||
  • [Decimal].format() formats the Decimal value into the locale of the current user. Is there a way of formatting a Decimal to an arbitrary locale (or format) in Apex? e.g. Decimal decimalValue = 10000.00; String stringValue = decimalValue.format('###,###,##0.00'); – cyorkston Apr 6 '16 at 16:03
  • @cyorkston not that I'm aware of. You'll have to roll out your own formatter, for example round down the number to cut into main & fractional part, then merge back with separators you need. Some dividing by 1000 until & adding comma till there's nothing to divide? Maybe you'll find some formatting functions or ideas at code.google.com/archive/p/apex-lang although the project is abandoned since 2012 and many functions it "patches" are now in core String library. – eyescream Apr 8 '16 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.