Citation :
David Schumann
04-Nov-2003 08:17
To evaluate math expressions (multiply, divide, addition, subtraction, percentages), use the following function, based on Taras Young's 'evalsum' function posted earlier:
Code :
function matheval($equation){ $equation = preg_replace("/[^0-9+\-.*\/()%]/", "", $equation); $equation = preg_replace("/([+-])([0-9]+)(%)/", "*(1\$1.\$2)", $equation); // you could use str_replace on this next line // if you really, really want to fine-tune this equation if ( $equation == "" ) { $return = 0; } else { eval("\$return=" . $equation . ";" ); } return $return; }
|
You could easily extend this to include exponents, square roots, or really any other mathematical function. I use it in a 'price each' field on a purchase order form. The user can type in '$10.00-25%' and get 7.50 as the result.
|