Re: math and modifier
| From: | Monte Ohrt | Date: | Sun, 11 Mar 2001 21:20:47 +0000 |
| Subject: | Re: math and modifier | ||
| References: | 1 | Groups: | php.smarty.general |
| Request: | Send a blank email to php-smarty-general+get-370@lists.php.net to get a copy of this message | ||
I have added an optional format attribute to the math function. use sprintf
format.
{math equation="x + y" x=1.1111 y=2.2222 format="%.2f"}
update your smarty_func_math in Smarty.addons.php to this one:
/*======================================================================*\
Function: smarty_func_math
Purpose: allow math computations in template
\*======================================================================*/
function smarty_func_math() {
$args=func_get_arg(0);
// be sure equation parameter is present
if(empty($args["equation"])) {
trigger_error("math: missing equation parameter");
return;
}
$equation = $args["equation"];
// make sure parenthesis are balanced
if(substr_count($equation,"(") != substr_count($equation,")")) {
trigger_error("math: unbalanced parenthesis");
return;
}
// match all vars in equation, make sure all are passed
preg_match_all("![a-zA-Z][a-zA-Z0-9]*!",$equation,$match);
foreach($match[0] as $curr_var) {
if(!in_array($curr_var,array_keys($args)) &&
!in_array($curr_var,array('int','abs','ceil','cos','exp','floor','log','log10',
'max','min','pi','pow','rand','round','sin','sqrt','srand','tan'))
) {
trigger_error("math: parameter $curr_var not passed as
argument");
return;
}
}
foreach($args as $key => $val) {
if($key != "equation" && $key != "format") {
// make sure value is not empty
if(strlen($val)==0) {
trigger_error("math: parameter $key is empty");
return;
}
if(!is_numeric($val)) {
trigger_error("math: parameter $key: is not numeric");
return;
}
$equation = preg_replace("/\b$key\b/",$val,$equation);
}
}
eval("\$smarty_math_result = ".$equation.";");
if(empty($args["format"]))
echo $smarty_math_result;
else
printf($args["format"],$smarty_math_result);
}
This will be in the next release of Smarty.
Maciek Uhlig wrote:
> Is it possible to apply a modifier to math tag result? What I want is to
> reduce number of decimal places in the division result. I can do it using
> numer_format() but how to apply number_format to {math equation="x/y"
> x=$block/var1 y=$block/var2} ?
>
> Maciek
>
> ---
> You are currently subscribed to smarty as: monte@ispi.net
> To unsubscribe send a blank email to $subst('Email.Unsub')
> Visit Smarty's homepage at
> http://www.phpinsider.com/php/code/Smarty/