Sunday, 5 June 2011

Decimal Rounding in an Apex


As I was asked by my colleague how to round any decimal to certain decimal point, he was new to Salesforce. I looked in Math Methods in Apex Lang Ref. but could not find any as Round method there only returns floor or celling integer value removing all the decimal points. Then I suggested him to basic mathematic formula that my teacher told me in 10th standard
1)Multiply your number with nth power of 10 where n is the decimal point up to which we want to round it.
2) Use Math.Round then
3)Again divide it with n th power of 10

He was amazed that is that the way we do these small things in Apex, his comment made me to go again to Apex Lang Ref. Now I found a direct method in Decimal Method

Do this in System Logs :
Decimal decimalvalue = 23.55564543;
//rounds it up to 3 decimal places
d = d.setscale(3);
system.debug('decimalvalue : ' + d.scale());

Debug Result -> decimalvalue : 23.556

Decimal decimalvalue = 23.55534543;
//rounds it up to 3 decimal places
d = d.setscale();
system.debug('decimalvalue : ' + d.scale());

Debug Result -> decimalvalue : 23.555

So to my colleague and all please use this one and don't complicate things :)



  1. small but very useful, thanks for sharing this :)

  2. Don't forget that Salesforce defaults the rounding mode to half-even which means 0.5 is rounded to 0 and 1.5 is rounded to 2.

    As an alternative, use,

  3. Thank you, chaps. Most useful that is.

  4. I'd appreciate if you share some links to other sources that carry info on this subject if you are aware of some.

  5. thank you for sharing such a nice and interesting blog with us. hope it might be much useful for us. keep on updating...
    SEO Company In Chennai


  6. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.

    Salesforce training in Chennai

  7. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.

    digital marketing course in chennai
    hadoop training in chennai


  8. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    Personal Installment Loans
    Payday Cash Advance loan
    Title Car loan
    Cash Advance Loan

  9. The information which you have provided is very good. It is very useful who is looking for salesforce Online Training Hyderabad