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

    kibitzer Correct answer

    9 years ago

    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.

    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_?

    Perfect, thanks. I've made an edit to include an example specifying the rounding mode as the web documentation doesn't.

    The code above, with HALF_UP specified, produces those results.

    It's worth noting that even though Salesforce calls this "HALF_UP", it is actually "Half Away from Zero" rounding. Traditionally "Half Up" rounds negative numbers differently, with -1.5 rounding to -1 (up; toward positive infinity). Salesforce's HALF_UP rounding, however, will round -1.5 to -2 (away from zero). Similar results are true of the other rounding methods in salesforce (DOWN == toward zero, UP = away from zero, etc..)

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used