1

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?

2 Answers 2

7

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
5
  • 1
    Nifty. I learned something new today (I don't work with decimals often).
    – sfdcfox
    Oct 14, 2021 at 23:33
  • 1
    @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?
    – Irene
    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
    – Derek F
    Oct 17, 2021 at 21:01
  • Thanks for the explanation Derek. How do I see the actual number in Debug?
    – Irene
    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.
    – Derek F
    Oct 17, 2021 at 21:36
2

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .