Skip to content

Instantly share code, notes, and snippets.

@mort3za
Last active October 26, 2021 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mort3za/0e6cc36ed5074c33baca8666dae70246 to your computer and use it in GitHub Desktop.
Save mort3za/0e6cc36ed5074c33baca8666dae70246 to your computer and use it in GitHub Desktop.
Human readable number format in Twig. Example: human_readable(22111, 1) ===> 22.1K
{% macro human_readable(input, fraction) %}
{% spaceless %}
{% set kilo = 1000 %}
{% set mega = kilo * 1000 %}
{% set giga = mega * 1000 %}
{% set tera = giga * 1000 %}
{% if input < kilo %}
{{ input ~ ' B' }}
{% elseif input < mega %}
{{ (input / kilo)|number_format(fraction, '.') ~ 'K' }}
{% elseif input < giga %}
{{ (input / mega)|number_format(fraction, '.') ~ 'M' }}
{% elseif input < tera %}
{{ (input / giga)|number_format(fraction, '.') ~ 'G' }}
{% else %}
{{ (input / tera)|number_format(fraction, '.') ~ 'T' }}
{% endif %}
{% endspaceless %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment