Format numbers depending on selected locale

AI-generated summary

In the thread titled ‘Format numbers depending on selected locale’, gerhard highlights that Discourse fails to format numbers according to the user’s configured locale, citing examples where German decimal separators (commas) and lowercase ‘k’ for thousands are ignored in view counts and polls. gerhard initially proposes using libraries like FormatJS or Numeral.js to address this, noting that Intl.NumberFormat lacks sufficient browser support, particularly on Safari and mobile devices. sam questions the necessity of adding a new library, suggesting instead that a solution could be implemented within the existing /lib/locale scripts. gerhard agrees that adding a library is not ideal and acknowledges that while Intl.NumberFormat is the ideal standard, a polyfill or a custom function in the locale scripts is a viable alternative. Finally, gerhard discovers that code capable of handling localized number formats already exists within the Discourse codebase but is currently unused, pointing to a specific implementation in the i18n.js file.

Continuing the discussion from Is there a way to translate numbers e.g. "1.3K" in the "Views" column?:

Looking at the code I noticed that numbers aren’t formatted using the locale configured by the user or administrator.
This can be seen at the reply and view counts. On a German locale it looks like this:

But it should look like this:

In German we use a comma as decimal separator. And of course, as @downey already mentioned the “K” should be a lowercase “k”. :wink:

The missing localization of numbers can also be seen in the poll plugin. The average rating uses the English decimal separator…

Could we use a library like FormatJS or Numeral.js in order to format numbers? Looks like not all major browsers support Intl.NumberFormat yet. :frowning:

3 إعجابات

hmmm why do we need to pull a whole new library in for this, we already have … /lib/locale/en.js etch… why not just add another method there.

Yeah, I guess adding another library isn’t the best option. In an ideal world we could just use Intl.NumberFormat, but of course Safari and all those mobile browsers lack support for it. :angry:

But FormatJS looks promising. It’s using a polyfill for Intl, integrates well with Ember and I’m quite sure it would be possible to replace moment.js with it too. (Ok, moment.js is currently used for parsing and calculating dates, so replacing it is probably not an option.)

Anyway, we need some kind of solution for this. If it’s just a “simple” function in those lib/locale scripts, that’s fine with me too.

Looks like there’s already some code that could handle localized number formats. It’s just not used…

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/locales/i18n.js#L353-L358

4 إعجابات