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
Marco SantosMarco Santos 

How to round a number?

Hi,
Could somebody help me round a number in my apex code?. Namely I have a number for example:
53732.99999999, then I would round this number to 53,733.00
Currently I am using the following code:
roundNumber.setScale(2,System.Roundingmode.DOWN).format(),
although is not formating the number correctly as I am receiving 53,732.99. Any help will be appreciated

Thank in advance
Best Answer chosen by Marco Santos
Vijay NagarathinamVijay Nagarathinam
Hi Macro,

Use setScale(0) simply 

For example:
 
decimal x = 55.9999999;
decimal y = x.setscale(0);
system.debug('@@@@@@@@@@@ set scale'+y);

 

All Answers

@anilbathula@@anilbathula@
Hi Marco,

Try this code:-

     Decimal d = 53732.99999999;
     Decimal i=Math.Round(d); 
     system.debug('Result::::::::::'+i);

Hope it works

Thanks
Anil.B
Marco SantosMarco Santos
Hi, thanks for the quick response. Could I ask if in the sample you posted is possible to round the number to
53733.00 rather than 53733 (currently this is how your example work)?

Thanks again
James LoghryJames Loghry

If you're attempting to display the decimal in Visualforce, you could use the apex:outputText to format the decimal with the way you desire.  For example:

<apex:outputText value=”{0, number,###,###,##0.00}”><apex:param value=”{!yourDecimalVariable}” /></apex:outputText>
The following will take the yourDecimalVariable member variable in your Apex controller and format it with trailing zeros.



 

MithunPMithunP
Hi Marco Santos,

Here is the updated code for rounding a number to TWO decimal places in apex.
Decimal initValue = 53732.99999999;
Decimal finalValue = initValue.setScale(2);
System.debug('+++++++++++Final Result++++++++++++'+finalValue);
Best Regards,
Mithun.
Vijay NagarathinamVijay Nagarathinam
Hi Macro,

Use setScale(0) simply 

For example:
 
decimal x = 55.9999999;
decimal y = x.setscale(0);
system.debug('@@@@@@@@@@@ set scale'+y);

 
This was selected as the best answer