Marshall Bowers

Conjurer of code. Devourer of art. Pursuer of æsthetics.

How Hard Is It to Format a Number?

Sunday, May 16, 2021
270 words
2 minute read

The answer, as it would appear, is "very".

Tonight I spun up a new stats page for my site. Since I already have word counts for all of the writing I post here, I wanted to sum them up to know how many words I've written in total.

Some quick and dirty hacking in Tera produced the numbers I needed, which then presented a problem: how do I format a number with comma separators?

My first instinct was to hunt for a Tera filter to do this. After all, this seemed very similar to date formatting. Scouring the Tera docs and GitHub issues left me empty-handed; apparently I'm the first person who wants to dynamically format numbers in a static site generator.

At this point I took a detour that revolved around me trying to remember high school math as I tried to implement a number formatting algorithm using Tera's macro system. It didn't take long before I labeled this a fool's errand and decided to give up.

In the end I resorted to using JavaScript's toLocaleString() to solve this issue:

(() => {
  const elements = document.getElementsByClassName('locale-num');
  for (let i = 0; i < elements.length; i++) {
    const n = parseInt(elements[i].textContent);
    if (!isNaN(n)) {
      elements[i].textContent = n.toLocaleString();

My only consolation is that this JavaScript snippet is the very definition of "progressive enhancement". If someone were to visit the page and not have JavaScript enabled, the worst that could happen is they have to squint a little harder to read some numbers.