1

There were many question around the topic of formatting decimals according to user's locale and rounding decimals, but I haven't seen the one that actually fits my case, so here I go.

I am creating custom, styled LWC table component to display data from SF object. There will be currency column, it looks like this:

enter image description here

The problem you can see in the picture above is it's difficult to read and compare numbers because of different number of decimal places.

Is there any way to print the number with respecting decimal separator from user's locale but also setting fixed number of decimal places? Decimal.format() part is easy, the fixed places are the main problem here.

P.S. I would rather have formatting done on backend due to design decisions already made.

1

Due to lack of response I decided to answer myself. Here's code that I've written to format decimals:

//format decimal according to user's locale setting fixed number of places
//note: places has to be positive number, for zero use round()
public static String formatFixedDecimalPlaces(Decimal d, Integer places) {
    //performance: better to substring() than to add '0' in loop
    final String ZERO_STR = '00000000000000000000000000000000000000000000000000000000';
    //check what is current locale's decimal separator
    final Decimal TEST_DEC = 0.001;
    String testStr = TEST_DEC.format();
    String decSeparator = testStr.substring(1, 2);
    
    //we are setting scale so the numbers with more decimal places will round
    String result = d.setScale(places).format();
    
    
    //find separator
    Integer sepIndex = result.indexOf(decSeparator);
    if(sepIndex == -1 && places != 0) {
        //no decimal places in source decimal
        result += decSeparator + ZERO_STR.substring(0, places);
    } else {
        //number of digits in source decimal
        Integer decimalDigits = result.length() - 1 - sepIndex; 
        Integer placesToAdd = places - decimalDigits;
        if(placesToAdd > 0) {
            //adding digits
            result += ZERO_STR.substring(0, placesToAdd);
        }
    }
    return result;
}

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.