Twig Number Format 将 double 转换为 int
Twig Number Format converts double to int
我正在尝试打印两个数字之间的差异。
直接打印时,两个数字都分配了一个值,并以逗号作为小数点分隔符:
{{ vals[1] }} --> 7,00
{{ vals[2] }} --> 6,63
为了能够用这些数字进行计算,我使用 |number_format (2, '.', ',')
将 ,
分隔符替换为 .
。但是,当我现在直接打印这些数字时,我得到一个 int 值
{{ vals[1]|number_format (2, '.', ',') }} --> 7.00
{{ vals[2]|number_format (2, '.', ',') }} --> 6.00
因此尝试计算这些值的差异我只得到 return 中的 int 值。
{% set diff = vals[1]|number_format(2, '.', ',') - vals[2]|number_format(2, '.', ',') %} --> 1.00
出于某种原因,我无法使用 number_format
设置正确的逗号分隔符。我最终使用 replace
代替:
{% set diff = (vals[1]|replace({',': '.'}) - vals[2]|replace({',': '.'})) %}
使用树枝number_format
is a direct mapping to number_format
(使用类型转换):
return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
^^^^^^^
参考:https://github.com/twigphp/Twig/blob/3.x/src/Extension/CoreExtension.php#L569
您提供的是一个字符串 "6,63"
,所以最终传递给 native number_format
的是:6.00
因为类型转换结果。
因此,如果您想在视图中使用 number_format
,请确保传递正确的 int
或 float
。否则 拥抱 值是一个字符串并使用字符串操作方法(如您的回答)。
这个例子应该有效:
{% set val1 = '7,00' %}
{% set val2 = '6,63' %}
{% set val1 = val1|replace({',': '.'}) %}
{% set val2 = val2|replace({',': '.'}) %}
result = {{ (val1 - val2)|round (2) }}
// output: 0.37
我正在尝试打印两个数字之间的差异。
直接打印时,两个数字都分配了一个值,并以逗号作为小数点分隔符:
{{ vals[1] }} --> 7,00
{{ vals[2] }} --> 6,63
为了能够用这些数字进行计算,我使用 |number_format (2, '.', ',')
将 ,
分隔符替换为 .
。但是,当我现在直接打印这些数字时,我得到一个 int 值
{{ vals[1]|number_format (2, '.', ',') }} --> 7.00
{{ vals[2]|number_format (2, '.', ',') }} --> 6.00
因此尝试计算这些值的差异我只得到 return 中的 int 值。
{% set diff = vals[1]|number_format(2, '.', ',') - vals[2]|number_format(2, '.', ',') %} --> 1.00
出于某种原因,我无法使用 number_format
设置正确的逗号分隔符。我最终使用 replace
代替:
{% set diff = (vals[1]|replace({',': '.'}) - vals[2]|replace({',': '.'})) %}
使用树枝number_format
is a direct mapping to number_format
(使用类型转换):
return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
^^^^^^^
参考:https://github.com/twigphp/Twig/blob/3.x/src/Extension/CoreExtension.php#L569
您提供的是一个字符串 "6,63"
,所以最终传递给 native number_format
的是:6.00
因为类型转换结果。
因此,如果您想在视图中使用 number_format
,请确保传递正确的 int
或 float
。否则 拥抱 值是一个字符串并使用字符串操作方法(如您的回答)。
这个例子应该有效:
{% set val1 = '7,00' %}
{% set val2 = '6,63' %}
{% set val1 = val1|replace({',': '.'}) %}
{% set val2 = val2|replace({',': '.'}) %}
result = {{ (val1 - val2)|round (2) }}
// output: 0.37