Reputation: 611
Not sure on how to do this within Smarty, but this is what i'm trying to do.
Deduct 25.5% from the price.
{math assign="$percentage" equation="(x - y)" x=$product.price y="25.5%" format="%.2f"}
{$percentage}
But i've found out that doing the
y="25.5%"
does not work, i've tried researching on the best practice, but so far nothing that i found that i understood...
Any ideas very welcome ;)
Upvotes: 0
Views: 1352
Reputation: 37710
You don't need to use math
or assign
, just do the calculation directly, though as Mark Baker said, $y
needs to be a number (0.255), not a percentage string:
{($product.price - ($product.price * $y))|string_format:"%.2f%%"}
You could put the percentage character outside the Smarty tag, but I've put it in the string_format
so it's self-contained.
Upvotes: 1
Reputation: 111829
First thing - if possible you should do such calculation in PHP and simple assign result to Smarty. In most cases it's the best way. You need to also notice:
{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.
But let's assume you still want to do it directly in Smarty
First thing, when you use assign in math you shouldn't use $
before variable name so it should be {math assign="percentage"
and not {math assign="$percentage"
You cannot use percentage in y so you need to do it this way:
{math assign="percentage" equation="(100-y)/100 * x" x=$product.price y="25.5" format="%.2f"}
{$percentage}
or this way
{math assign="percentage" equation="(1-y/100) * x" x=$product.price y="25.5" format="%.2f"}
{$percentage}
or you simple should pass not 25.5 as y but already divide it by 100 so 0.255 as below
{math assign="percentage" equation="(1-y) * x" x=$product.price y="0.255" format="%.2f"}
{$percentage}
All those method generate the same, expected result.
Upvotes: 1
Reputation: 59699
I'm not at all familiar with Smarty, but you need to multiply the price by the percentage (expressed as a decimal value from 0 to 1) to get the discount, then subtract that value from the original price. So, the equation you're looking for is:
x - (.255 * x)
Which may or may not work within Smarty:
{math assign="$percentage" equation="(x - (.255 * x))" x=$product.price format="%.2f"}
Upvotes: 0