DEV Community

Cover image for A Svelte component to format numbers
Mike
Mike

Posted on • Originally published at mikenikles.com

6 1

A Svelte component to format numbers

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay