5

I'd like to format a currency value that a user inputs in a modal dialog as part of a lightning-datatable field that is composed of some fixed text and that currency value.

But AFAIK there are no JavaScript APIs in LWC for this kind of thing: it is assumed that such formatting is always part of a template via e.g. lightning-formatted-number with the results directly output.

Is hand-crafted code or using a 3rd party library and finding ways to hook in the user's locale the only way to go here?

5

You can access the user's locale via the i18n library methods, which you can then pass in to LWC datatable's typeAttributes:

import USERLOCALCURRENCY from '@salesforce/i18n/currency';

...

{ label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode: USERLOCALECURRENCY }},
| improve this answer | |
  • Are there any other libraries that are available for us like the i18n? Is there a list somewhere? – Arthlete Jun 30 at 19:39
  • 1
    @Arthlete That's Salesforce's only offering. It's possible to write a custom cell type + a library like globalize to provide custom logic, or you can mix-and-match using the two techniques. I'd recommend starting with i18n + the built-in attributes to see if it meets a project's need before going off the beaten path. – sfdcfox Jun 30 at 19:44
  • 3
    @Arthlete il8n is provided by Salesforce so it will likely be the best experience for working with LWCs. There are a number of internationalization JS libraries out there but finding one that plays well with LWCs may be a challenge. There are a handful on the awesome-javascript list. github.com/sorrycc/awesome-javascript#i18n-and-l10n – nbrown Jun 30 at 19:45
  • @nbrown Thanks for your input. I'm going to check out that library myself. We don't use i18n in our org, but I'm envisioning a time in the near future where a personal project of mine will need it. – sfdcfox Jun 30 at 19:46
  • Thanks all for this input. I'm looking for something quite small to just do data formatting; interesting to see the work going into e,g, pluralisation. Something like github.com/formatjs/formatjs may be a better starting pint given that it is broken out into lots of packages. – Keith C Jun 30 at 19:54

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.