kaisermann / svelte-i18n

Internationalization library for Svelte
MIT License
1.26k stars 80 forks source link

Usage of short numbers #14

Closed brunoamancio closed 4 years ago

brunoamancio commented 5 years ago

Is it possible to format numbers with B for billion, M for million, K for thousands?

For example, 3200000 shoud be 3,2M

kaisermann commented 5 years ago

Currently there's no way of formatting numbers with a compact notation (look for compact here). It seems that this API is experimental, so intl-formatmessage doesn't offer support for it.

For now, I can expose an API to create custom formatters in the user-land. To do this, it'd probably be a breaking-change, since I'd need to modify the signature of the _ methods.

kaisermann commented 5 years ago

Something like:

1) When initialising the i18n store, add some custom formats (number or date or time). The format props will be passed directly to the Intl.NumberFormat or Intl.DateTimeFormat.

import {
  dictionary,
   ...,
  addCustomFormats,
} from 'svelte-i18n'

addCustomFormats({
  number: {
    compact: {
      notation: 'compact',
      compactDisplay: 'long',
    },
  },
})

2) On your template, call the _.number method specifying the format:

Number util: {$_.number(10000, { format: 'compact' })}
kaisermann commented 5 years ago

This change can bring some flexibility, but it includes having to rewrite all interpolated translations from:

$_('path.to.message', { name: 'John', lastname: 'Doe' })

to

$_('path.to.message', { values: { name: 'John', lastname: 'Doe' }}).

The first argument is still the message path on the dictionaries, but the second (interpolations) and third (locale) args become a single object which can receive any kind of props, like format. This way, you wouldn't need to pass null for interpolations in case of wanting to force a locale$_('message', null, 'pt-BR')

kaisermann commented 5 years ago

Played around a bit and you can test a version of what I said above in the https://github.com/kaisermann/svelte-i18n/tree/feat/options-object branch.

brunoamancio commented 5 years ago

It's more flexible with the ability to include custom formats :) The breaking changes could also released in a new version, so people using the older signatures can explicitly migrate, if needed. PS.: I'm Brazilian as well, but live in the EU :)