A Svelte component to format numbers
Let’s develop a Svelte component that formats numbers in a human readable way.
Instead of 63476432, the component displays 64M. Here are a few more examples:
| 6 | => | 6 |
| 63 | => | 63 |
| 634 | => | 634 |
| 6347 | => | 6.3K |
| 63476 | => | 63K |
| 634764 | => | 635K |
| 6347643 | => | 6.3M |
| 63476432 | => | 63M |
It supports different locales as well. Converting 63476432 looks as follows:
| ko-KR | => | 6348만 |
| zh-TW | => | 6348萬 |
| de-CH | => | 63 Mio. |
| ar-SA | => | ٦٣ مليون |
How it’s done
We leverage the Number.prototype.toLocaleString() method (docs). Thanks to that, the Svelte component becomes very basic:
<script>
export let number;
export let locale = 'en';
$: formattedNumber = number.toLocaleString(locale, {
notation: 'compact',
compactDisplay: 'short'
});
</script>
<style>
span {
font-variant-numeric: tabular-nums;
}
</style>
<span>{formattedNumber}</span> It is important to make sure number is of type Number. If you pass a string, the toLocaleString method will not work as intended.
Typescript
I highly recommend you enable Typescript for your Svelte project (instructions) and refactor the FormattedNumber component as follows:
<script lang="ts">
export let number: number;
export let locale: string = 'en';
$: formattedNumber = number.toLocaleString(locale, {
notation: 'compact',
compactDisplay: 'short'
});
</script>
<style>
span {
font-variant-numeric: tabular-nums;
}
</style>
<span>{formattedNumber}</span> Voilà, now the Typescript compiler makes sure you pass a Number.
