[SalesForce] Round a Decimal to two decimal places

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);

Best Answer

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.