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
TehNrdTehNrd 

How to round a number to two decimal places?

Part of this is me struggling with the syntax and the other part is me not knowing what system method to use. A decimal method, math method?

Code:
Decimal parentlistPrice = 9995.00
Decimal svcPercent = .17
Decimal discount = .88
//oli.quantity = 2.0
        
oli.TotalPrice = ((parentListPrice * svcPercent) * discount) * oli.Quantity;

oli.TotalPrice  will equal 2990.504 but I would like to round this to only two decimal places so the value is 2990.50
 

Best Answer chosen by Admin (Salesforce Developers) 
TehNrdTehNrd
That did the trick. I thought I had tried this but I just didn't get my syntax right.

Here is the correct code:

oli.TotalPrice = (((parentListPrice * svcPercent) * discount) * oli.Quantity).setScale(2);



All Answers

ryanhallmanryanhallman
The setScale method should do it for you.

http://www.salesforce.com/us/developer/docs/apexcode/index.htm

Cheers,
Ryan
TehNrdTehNrd
That did the trick. I thought I had tried this but I just didn't get my syntax right.

Here is the correct code:

oli.TotalPrice = (((parentListPrice * svcPercent) * discount) * oli.Quantity).setScale(2);



This was selected as the best answer
miteshsuramiteshsura

thanks, I was going crazy on fig-ing this out ..

RajgottipoluRajgottipolu

 

Hi People,

 

Is there any way i can use it for input fields too?

 

Here is the problem im having:

 

I enter a decimal value 10 for an inputfield and click next to go to another block. and when i click back..the input field shows '10.0' instead of '10.00' even though im using setscale(2). any thoughts on this? 

Bhawani SharmaBhawani Sharma
Why don't you mark this field as 16,2 on database level? That will convert your field value to 10.00 automatically without a single line of code.
Bryan Leaman 6Bryan Leaman 6
Bhawani, That will only set it to 2 decimal places for display. Internally the database stores more decimal places and will use them in calculations involving that field.