Apex Decimal – How to Round Up Decimal to Nearest 1000?

apexdecimalroundingvisualforce-component

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?

Best Answer

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