Until today I was very happy with this utility method

public static string roundNumber(decimal d, integer precision) {
    if(d == null) return '';
    string separator = (1.01).format().substring(1,2)  ;
    string pre          = d.setScale(precision,System.RoundingMode.HALF_UP).format();
    string fraction     = pre.substringAfter(separator).rightPad(precision).replace(' ','0');
    string nonFraction  = pre.substringBefore(separator);
    if(precision==0) separator = '';
    return ''+nonFraction + separator + fraction;

But I've noticed that it does not work well with precision > 3


Decimal d = 123.456789;

It renders fine

roundNumber(d,3); // ==> '123.457'

But not okay with

roundNumber(d,4); // ==> '123.4570'

In my research I found, that d.setScale() is working as expected and unless you don't use .format() everything is fine. But .format() kill all decimals after the 3rd decimal place.

Strangely this is even documented in the manuals here https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_decimal.htm

// U.S. locale Decimal myDecimal = 12345.6789; system.assertEquals('12,345.679', myDecimal.format());

I see this as a flaw but it looks like it's "as designed" and it's probably one of those features I can hardly understand...

Has anyone an idea on how to localized-format-output any decimal with any given precision?

  • Is there a locale that will format the fraction component of the number with any type of separator? I've seen lots of variation on the nonFraction component, but never any locale unique formatting paste the separator. It may well be that I just haven't seen formatting for a sufficient number of locales yet, but it might make your like easier if you didn't need to format the fraction. Oct 24, 2018 at 19:42
  • We need to display currency on PDF and preserve the trailing zeroes. For example, 1000.00 should be displayed as $ 1,000.00, but .format() removes the trailing zeroes and prints $ 1,000 which is not acceptable. Nov 28, 2023 at 20:48

1 Answer 1


I talked with @ca_peterson, the Salesforce Apex Product Manager, who confirmed that what you're asking for is not possible today. He said there's an idea Have Decimal.format() print more than 3 decimals which should be voted up if you want to see this prioritized on the roadmap.

You must log in to answer this question.

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