简体   繁体   中英

How to format double in Salesforce Apex

I want to display double in format such as "12.30" but it display "12.0" in salesforce apex. can any one help me?

VisualForce uses the java.text.MessageFormat conventions for formatting. Here's an example. Replace the MyDouble variable with your own.

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

You can cast the 12.30 as an int and then cast it back to double. Casting it to an int truncates the fraction.

double i = 10.345;
system.debug('this is i '+ i);
system.debug('this is i after fixing '+ (double)(integer)i);

gives:

10:04:26.129 (129990000)|USER_DEBUG|[16]|DEBUG|this is i 10.345
10:04:26.130 (130080000)|USER_DEBUG|[17]|DEBUG|this is i after fixing 10.0

When you are creating a field then we have to define it's decimal places. Try specifying that decimal number to 2. It will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM