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

formatting numbers for display in Visualforce page - commas for thousands, etc.

If you are displaying a field from an sObject, <apex:outputField> does a nice job of adding decimal points and commas for thousands, etc.

If you are displaying your own variable (decimal), you cannot use <apex:outputField> becuase it is not part of an sObject.

Is there some easy way to add formatting to change 123456.78 into 123,456.78 dynamically? Do I need to convert the number to a string and then manipulate? Do I need to use JS to modify client-side? These would work but seem heavy-handed for what see be a common requirement.
You could just use the entire object a variable.

Using just decimal:
Decimal number = 5.453; Decimal sum = number + 2; Using opportunity as a container for your variable:
Opportunity opp = new Opportunity(); opp.Amount = 5.453; Decimal sum = opp.Amount + 2;


Message Edited by TehNrd on 11-07-2008 04:20 PM
This works (thanks), but boy do I feel dirty using it as a hack. I shouldn't need to create a complex data object (opportunity) just to format a number string.
The answer is to use the Decimal method format() (e.g. myDecimal.format() ), which returns a string with inserted commas.

The new problem is that this method doesn't allow you to display (for example) exactly 2 decimal places. So you end up with a visualforce-displayed table of values that looks like this:

234,567.9 (instead of 234,567.90)
987,654 (instead of 987,654.00)

If there's some way to force display of exactly 2 decimal places (and still have the commas that get there via the format() method), I'd like to know.

I wrote a function to do this, it's pretty lame but it works. I'm sure some genius out there could optimize it or come up with a better method.



public static String formatDouble(Double num, Integer decimalplaces) { Double multiplier = Math.pow(10, decimalplaces); num = num*multiplier; Long rounded = Math.roundToLong(num); num = rounded/multiplier; String formated = Decimal.valueOf(num).format(); //add zeros if needed Integer dotIndex = formated.indexOf('.'); if(dotIndex < 0) { formated += '.'; for(Integer i=0; i<decimalplaces; i++) { formated += '0'; } } else { Integer needed = decimalplaces - formated.substring(dotIndex+1).length(); for(Integer i=0; i <needed; i++) { formated += '0'; } } return formated; }