4

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

With

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?

1
  • 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. – Daniel Ballinger Oct 24 '18 at 19:42
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.