phpsmartypercentagephp-5.4smarty2

Add on a percentage to a variable value in Smarty 2 template


I have assigned a variable in my Smarty 2 template.

{assign var="real_count" value="{$store_summary|@count}"}
{$real_count = settype ($real_count, 'integer')}

My goal is to add on 65% to the value of $real_count. With the data i'm working with I have a $real_count of 3, so the calculated value should be 4.95 (3 + 1.95).

I am attempting to use the math tag, however I am clearly missing something.

{math equation="x * y" x=$real_count y=0.65 format="%.2f"}

Solution

  • If you really want to do this within the Smarty template, you can solve it like this (slightly simplified):

    {assign var="real_count" value="3"}
    {math equation="x + (x * y)" x=$real_count y=0.65 format="%.2f"}
    

    However, I would usually advise against doing too much math and other logic in a template. In most use cases, it would be better to do the math within the application and then display the result within the template. Even the Smarty manual agrees with me:

    math is an expensive function in performance due to its use of the php eval() function. Doing the math in PHP is much more efficient, so whenever possible do the math calculations in the script and assign() the results to the template. Definitely avoid repetitive math function calls, eg within section loops.