function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ralph CallawayRalph Callaway 

String.format() breaks when passing actual format strings

Anyone out there able to get String.format() to work with actual format strings as supposed to basic substitutions?  

 

This works fine and outputs "Name foo, Value bar"

 

String formatString = 'Name {0}, Value {1}';
List<String> inputs = new String[] { 'foo', 'bar' };
system.debug(String.format(formatString, inputs));

 But this blows up with this error: "System.StringException: Cannot format given Object as a Number"

 

String formatString = 'Percent: {0, number, percent}';
List<String> inputs = new String[] { '.85' };
system.debug(String.format(formatString, inputs));

I'm trying to build a user interface that will dynamically format it's output.  I'd hope to have use String.format() to accomplish this.

 

 

Am I making a syntax error or doing something else wrong?

 

bob_buzzardbob_buzzard

I think that the String.format is somewhat more limited than the apex:outputtext in this regard.   Looking at the docs, the String.format function takes an array of strings as its arguments, rather than an array of objects (e.g. decimals, dates). Thus the only formatting that is available is to output it as a String to replace a {0}, {1} etc.

Ralph CallawayRalph Callaway

Not what I was hoping to hear, but a valid point.  It's a shame we aren't able to use Java MessageFormat from within apex.  I've got a lot of use cases it would really simplify things for.