DEV Community

loading...
Cover image for A Svelte component to format numbers

A Svelte component to format numbers

Mike Nikles
Software Architect πŸ‘·. Productivity ⏱️ & Team Morale 😊. Web, Javascript, Cloud Native ☁️. Author πŸ“š and Educator πŸ§‘β€πŸ«.
Originally published at mikenikles.com ・2 min read

Photo by Nick Hiller on Unsplash

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

VoilΓ , now the Typescript compiler makes sure you pass a Number.

Discussion (0)