+ Start a Discussion
James L.James L. 

How to format Integer 12000.0 to string 12,000.0 using Apex

Hi,
In visualforce, there's code like

This can be used for string output formatting.

Is there simillar one in Apex, like

Dicimal d = 4000.0;
How can I convert it to a string like '4,000.0'

I tried 2 ways, both failed
1) d.format() , this will be displayed like '4,000'
2) String.format: don't know how to use this API. There's no document from SFDC about this

Best Answer chosen by Admin (Salesforce Developers) 
jbroquistjbroquist

Your initial feeling was right to go with the format() method. Try this code out:

 

Decimal d = 1234.56;
List<String> args = new String[]{'0','number','#,###.0'};
String ds = String.format(d.format(), args);
system.debug(ds);

 

All Answers

James L.James L.
Sorry, it's decimal 12000.0 not integer 12000.0
James L.James L.
any similar stuff in apex like following in VF

<apex:outputText value="{0, number, #,###.0}">
<apex:param value="{!aa}" />
</apex:outputText>
ian b goodeian b goode

Try one of these:

 

String,valueOf(<integer or decimal>);

<decimal>.toPlainString();

jbroquistjbroquist

Your initial feeling was right to go with the format() method. Try this code out:

 

Decimal d = 1234.56;
List<String> args = new String[]{'0','number','#,###.0'};
String ds = String.format(d.format(), args);
system.debug(ds);

 

This was selected as the best answer
James L.James L.
{'0','number','#,###.0'} works for numbers like "1234.5" , but NOT for numbers like "1234.0".

I tried {'0','number','#,###.0'} in both VF and Java. All worked, but Apex didn't work.

The reason is
Decimal d = 1234.0
d.format() -> always converted to "1234", instead of "1234.0"
James L.James L.

didn't work.
1234.0 will always be converted to "1234" not "1,234.0"