goal:
write the most concise function that formats a (String) decimal into a currency format in Apex. Feel free to trainwreck the code for points, I've kept mine exploded for readability purposes.
|
|
Here's one that's shorter AND is locale safe:
Check out Number Format in the list of supported locales. There's "1.000,00" and "1 000.00" amongst others. Not everyone uses "1,000.00" so we shouldn't assume that in a formatter. Decimal's format() method is locale aware. |
|||||||||||
|
|
Ok - first, I'm not actually recommending the following approach. It's more of an intellectual exercise - an exploration of a different path to a solution. First, create the following Apex page:
The controller is as follows:
Here's some simple code to use it:
You still need to parse out the actually currency value - but that's easy enough to do use a regular expression or some substring work, so I left it out here. I also cheated by using an exception handler instead of the (better) validation shown in other answers - just to keep things simple. What does this approach accomplish?
Again - If I really needed this I'd probably actually write the code to lookup currency symbols, examine the current and corporate currency, and do the necessary conversions and formatting directly. But that's quite a bit of code (especially on orgs using advanced currency management). Ultimately my point is - the original question was asking for formatting a decimal string into currency format, and the job isn't really done until you have the correct currency symbol and multi-currency handling in place :-) |
|||
|
|
|
Of course, it all depends on your use case. Most of the time, you don't need to do this in Apex since the value is destined either for display on a VisualForce page or storage via a Currency field. That said, you'd be able to do this in pure Apex if it weren't for the type restriction on the String.format(...) method. Requiring a List<String> for the arguments prevents you from doing it in pure Apex, at least easily. If the point of the Apex code is to provide a value for display in a VisualForce page, then Apex really need not do anything but provide the raw decimal value:
No need for a dummy SObject with a currency field, although that certainly works. |
|||
|
|
670 characters
|
|||||
|
|
The following should do the trick, with the assumption that your locale for currency formatting is correct. Edited to handle null being passed, and zero values after the decimal.
|
|||||||
|
|
Rarely should you ever need to format variables like that in Apex. Since that's typically a view issue, I tend to rely on apex:outputField for that scenario in Visualforce. Kibitzer has the right idea. |
|||
|