Tell me more ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

How can I round an arbitrary Decimal to 2 decimal places (hundredths of a dollar)?

My first thought was to use the Math Functions ROUND(number, numDigits):

Decimal toRound = 3.14159265359;    
Decimal rounded = Math.round(toRound, 2);
system.debug(rounded);

But that produced the following compile error:

Compile error at line 2 column 19

Method does not exist or incorrect signature: Math.round(Decimal, Integer)

When I think of rounding I typically expect "Round half away from zero" tie-breaking behaviour. Maybe this isn't the best rounding approach to use with currency values? I would expect the following rounding:

  • 1.004 to 1.00
  • 1.005 to 1.01
  • 1.014 to 1.01
  • 1.015 to 1.02

The following works (to some degree), but seems a bit crude:

Decimal toRound = 3.14159265359;    
Decimal rounded = Math.round(toRound * 100) / 100.0;
system.debug(rounded);
share|improve this question

1 Answer

up vote 8 down vote accepted

I don't think it gets more concise than this:

Decimal toround = 3.14159265;
Decimal rounded = toround.setScale(2);
system.debug(rounded);

What's nice about this one is you can use the setScale overload that lets you specify the rounding mode you want to use.

Decimal toround = 3.14159265;
Decimal rounded = toRound.setScale(2, RoundingMode.HALF_UP);
system.debug(rounded);

In this case - I think you'll want the HALF_UP rounding mode. It's the traditional round to nearest, but round .5 up.

share|improve this answer
That does seem to be the common rounding method. Is there a rounding mode that would round 1.005 to 1.01 and 1.015 to 1.02? As in round half away from zero? – Daniel Ballinger Aug 29 '12 at 0:10
Perfect, thanks. I've made an edit to include an example specifying the rounding mode as the web documentation doesn't. – Daniel Ballinger Aug 29 '12 at 0:28
2  
The code above, with HALF_UP specified, produces those results. – kibitzer Aug 29 '12 at 8:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.