【问题标题】:Twig number format without rounding decimals没有四舍五入小数的树枝数字格式
【发布时间】:2016-01-21 11:18:41
【问题描述】:

如何在不四舍五入的情况下在 twig 中格式化数字? 例如,如果用户输入

12345.35,输出应该是 12,345.35

12345.356,输出应该是 12,345.356

12345.3567,输出应该是 12,345.3567

我尝试了 number_format 过滤器,但第一个参数是小数应四舍五入的精度。如果我使用12345.35|number_format(4, '.', ','),结果是 12,345.3500,这不是所需的输出。

【问题讨论】:

    标签: twig number-formatting


    【解决方案1】:

    您应该在格式化之前确定数字中的小数位数。不太明显,但我没有找到其他解决方案。

    试试这个宏:

    {% macro show_number(n) %}
      {%- spaceless %}
        {% set decimals = n | split('.')[1] | default('') | length %}
        {{ n | number_format(decimals, '.', ',') }}
      {% endspaceless -%}
    {% endmacro %}
    

    可运行示例here

    【讨论】:

    • 太棒了。效果很好。为演示 +1。
    猜你喜欢
    • 2011-01-28
    • 2022-12-03
    • 1970-01-01
    • 2015-11-12
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多