# How do I round up a Decimal to the nearest 1000 in Apex code?

I have a Visualforce PDF page with decimal values in it and these need to be rounded to the nearest 1000.00. If I do `decimal x = Math.round(x)` it just takes it to the nearest value on the left.

Eg I have

• 1,243,478.80 and need it rounded up to 1,243,000.00
• 1,243,578.80 and need it rounded up to 1,244,000.00

How do I achieve this?

The decimal class has the `setScale()` method. It's usually used to set the number of decimal places to be used, but you can pass it a negative number to round to the nearest 10, 100, 1000, etc...

``````Decimal d = 1234.56;
system.debug(d.setScale(-3)); // 1000
system.debug(d.setScale(-3, RoundingMode.CEILING)); // 2000
``````
• Nifty. I learned something new today (I don't work with decimals often). Oct 14, 2021 at 23:33
• @Derek F if I use your method and run it the debug returns this 'DEBUG|1E+3' - do I need to reformat or something to get it to display as a decimal? Oct 17, 2021 at 20:54
• @Irene It still is a decimal. The scientific notation is just an artifact of serialization that happens when `system.debug()` is called Oct 17, 2021 at 21:01
• Thanks for the explanation Derek. How do I see the actual number in Debug? Oct 17, 2021 at 21:30
• @Irene In general, you shouldn't worry too much about how `system.debug` displays things. '1E+3' is precisely the same as '1000'. If it is an issue in your PDF/Visualforce, then you could cast it as an `Integer` after rounding to the nearest target value. Oct 17, 2021 at 21:36

To get the nearest thousand, divide by 1000, round, and then multiply by 1000:

``````Decimal y = (x/1000).round()*1000;
``````

To get the next highest thousand (towards positive infinity), you can round up:

``````Decimal y = (x/1000).round(RoundingMode.CEILING)*1000;
``````

You can also read more about RoundingMode for other options, such as rounding away from zero.

• Great - works like a charm Oct 14, 2021 at 23:13