Last active
October 26, 2021 14:50
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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