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
SoporteICOSoporteICO 

Format currency into string decimal problem

I'm having an issue when formating currency in Apex.

 

I have this method in my VF extension:

public String getPrice(){
     List<String> formatter= new String[]{'0','number','###,###,##0.00'};
     String priceT = String.format(this.aux.Total_Price__c.format(), formatter);
     return priceT; 
}

The Total_Price__c field is currency type from a custom object.

I set the variable output to the VF page with:

<apex:pageBlockSectionItem >
    <apex:outputLabel value="Total Price"/>
    <apex:outputText value="{!price}"/>
</apex:pageBlockSectionItem>

 

My problem is that if the price has only zeros in decimal places it shows the number as an integer (no decimals at all), also if the price has more than 2 decimals the output shows all of them.

 

I want to always show 2 decimals no matter what.  

 

Best Answer chosen by Admin (Salesforce Developers) 
mcrosbymcrosby

Is there a need for you to perform the formatting in Apex code?  You could handle this in Visualforce using:

 

<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!price}"/>
</apex:outputText>

 Here is a sample page with a few examples of numbers formatted in the Visualforce page:

<apex:page >
<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!1}"/>
</apex:outputText>
<br/>
<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!0}"/>
</apex:outputText>
<br/>
<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!1.0}"/>
</apex:outputText>
<br/>
<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!1.012}"/>
</apex:outputText>
<br/>
<apex:outputText value="{0,number,#,##0.00}">
    <apex:param value="{!12345678945461.012}"/>
</apex:outputText>
</apex:page>

 Here is the resulting output:

1.00 
0.00 
1.00 
1.01 
12,345,678,945,461.01