Skip to content

Language function math

{math} 是一个在模板中执行数学运算的函数。

属性

属性名 必需 描述
equation 要执行的数学运算表达式
format 结果的格式(sprintf 格式)
var 数学运算中的变量值
assign 将输出分配给的模板变量
[var ...] 数学运算中的变量值
  • 可以在方程中使用任何数值模板变量,并将结果打印在标签的位置。

  • 方程中使用的变量作为参数传递,可以是模板变量或静态值。

  • +-/*absceilcosexpfloorloglog10maxminpipowrandroundsinsqrtsranstan 都是有效的运算符。有关这些 math 函数的更多信息,请参阅 PHP 文档。

  • 如果提供了 assign 属性,{math} 函数的输出将分配给该模板变量,而不是输出到模板中。

注意

由于使用了 PHP 的 eval() 函数,{math} 是一个性能较差的函数。在 PHP 中进行数学计算要更高效,因此尽可能在脚本中进行数学计算,并将结果通过 assign() 分配给模板。绝对要避免重复的 {math} 函数调用,例如在 {section} 循环内部。

示例

示例 1

{* $height=4, $width=5 *}

{math equation="x + y" x=$height y=$width}

上面的示例将输出:

9

示例 2

{* $row_height = 10, $row_width = 20, #col_div# = 2, assigned in template *}

{math equation="height * width / division"
    height=$row_height
    width=$row_width
    division=#col_div#}

上面的示例将输出:

100

示例 3

{* 您可以使用括号 *}

{math equation="(( x + y ) / z )" x=2 y=10 z=2}

上面的示例将输出:

6

示例 4

{* 您可以在 sprintf 格式中提供格式参数 *}

{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}

上面的示例将输出:

9.44