Format Jekyll/Liquid number needing commas included

40 Views Asked by At

I'm trying to format numbers that are custom variables in Jekyll's Front Matter to use a comma after every third digit. Ex. 1,000,000. My number is declared in the Front Matter like this:

---
my_number: 1000000
---

It's then retrieved on the page like this:

{{ page.my_number }}

As expected, the output is 1000000. There's plenty of Jekyll documentation about date formatting but little to none on numeric formatting. Is there a way to format that to 1,000,0000 without the need for a Jekyll plugin?

1

There are 1 best solutions below

0
Matt Smith On BEST ANSWER

Since Jekyll doesn't format number numbers to use commas without assistance from plugin I opted to reformat the numeric values using JavaScript.

function numberWithCommas(value) {
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

function updateNumericValues() {
    const myNumber = document.querySelectorAll('.myNumber');
    myNumber.forEach((e) => {
        const numericValue = e.textContent;
        const formattedValue = numberWithCommas(numericValue);
        e.textContent = formattedValue;
    });
 }

 updateNumericValues();