Search code examples
jekyllliquid

Trailing zero's in Jekyll/Liquid


I have frontmatter that looks like this:

products:
- item: item name
  price: 39.50
- item: item number two
  price: 12.50

How can I output these variables in liquid with trailing zero's?

Note that {{ products[0].price }} will output 39.5. I need it to output 39.50.


Solution

  • This would be one way to do it, in multiple steps:

    • Round the number N decimal places (e.g. 2) so decimals have a uniform size;
    • Split the number by the decimal separator, so you get an array with two elements, with the integral part on element 0, and the fractional part on element 1;
    • Append N trailing zeros to the fractional part, and truncate the string by N, so you get exactly N decimals.

    {% assign price_split = page.products[0].price | round: 2 | split: "." %}
    {% assign integral = price_split[0] %}
    {% assign fractional = price_split[1] | append: "00" | truncate: 2, "" %}
    
    Formatted Price: {{ integral }}.{{ fractional }}