Skip to content

Instantly share code, notes, and snippets.

@hexerei
Created May 26, 2017 10:16
Show Gist options
  • Save hexerei/5bd632b2a179717e219fbe18c5793181 to your computer and use it in GitHub Desktop.
Save hexerei/5bd632b2a179717e219fbe18c5793181 to your computer and use it in GitHub Desktop.
Liquid number format with thousands and decimal seperator

Liquid number format with thousands and decimal seperator

Based on the Gist by johnteske: https://gist.github.com/johnteske/aab61e8a43ca54dc30ac04888a29cbf1

My implementation uses the same thousand seperator routine, but extends it by allowing decimals and conversion of u.s. (i.e. 1,000.00) to european (i.e. 1.000,00) notation. In this implementation the default values are set to european style, which is easily adaptable in the liquid template via parameters or in the include by setting the defaults

Parameters

number

The number you want to display, expected integer or decimal format i.e.

1
3459
12450.45
3.5
7.000304

numdecimals

How many decimal places you want to display, expected 0 to 10 max (code can be adapted to allow more than 10)

ts

The thousands separator, defaults to '.'

ds

The decimal separator, default to ','

<h1>Usage Template</h1>
<h2>With integer to decimal conversion</h2>
<p>
{% include numf.html number=12345 %} <!-- output is 12.345,00 --><br />
{% include numf.html number=12345 decimals=0 %} <!-- output is 12.345 --><br />
{% include numf.html number=12345 decimals=4 %} <!-- output is 12.345.0000 --><br />
{% include numf.html number=12345 ds='.' ts=',' %} <!-- output is 12,345.00 --><br />
</p>
<h2>Using decimals</h2>
<p><strong>NOTE! numbers are automatically rounded</strong></p>
<p>
{% include numf.html number=12345.6789 %} <!-- output 12.345,68 --><br />
{% include numf.html number=12345.6789 decimals=0 %} <!-- output 12.346 --><br />
{% include numf.html number=12345.6789 ds='.' ts=',' %} <!-- output is 12,345.68 --><br />
</p>
{% assign ds = include.ds | default:',' %}{% assign ts = include.ts | default:'.' %}{% assign numdecimals = include.decimals | default:2 %}{% assign parts = include.number | round:numdecimals | split:'.' %}{% assign digits = parts[0] | split:'' %}{% for digit in digits %}{% assign threeFromEnd = digits.size | minus:forloop.index | modulo: 3 %}{% if threeFromEnd == 2 and forloop.index != 1 %}{{ digit | prepend: ts }}{% else %}{{ digit }}{% endif %}{% endfor %}{% if numdecimals > 0 %}{{ ds }}{% if parts.size == 1 %}{% assign decs = '0000000000' %}{% else %}{% assign decs = parts[1] | append:'0000000000' %}{% endif %}{% assign digits = decs | split:'' %}{% for digit in digits limit:numdecimals %}{{ digit }}{% endfor %}{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment