Apex RoundingMode

One of the things that always sends me searching through my old code is rounding. I can never remember the syntax and the Apex documentation on Decimal methods on the Salesforce Developer site doesn't provide any examples inthe description (Its somewhat hidden up in the Divide method description if you look for it) . So, I thought I'd put a few examples here as a reminder to myself and to share with everyone else Googling it. 

Decimal numberToRound = 12.345;
Decimal roundedUp = numberToRound.round(roundingMode.UP); //result: 13
Decimal roundedDown = numberToRound.round(roundingMode.DOWN); //result: 12
Decimal scaled = numberToRound.setscale(0); //result: 12 – no rounding specified, just removes decimal places
Decimal scaledUp = numberToRound.setscale(0, roundingMode.UP); //result: 13 – no rounding, just removes decimal places

Look at the documentation on the RoundingModes for more detail on Ceiling, Half_Down, Half_Up, etc. 

 

 

Advertisements
This entry was posted in Salesforce, Web/Tech and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s