You are here

function mathfield_evaluate in Math Field 7

Evaluate a math expression.

Parameters

string $expression: The math expression to evaluate.

array $settings: An array of math field settings. Keys include:

  • scale: The number of digits to the right of the decimal.
  • decimal_separator: The character to mark the decimal point.

array $replacements: An array of token replacements for the expression.

Return value

string|bool The formatted result of the expression or FALSE on error.

2 calls to mathfield_evaluate()
mathfield_form_afterbuild in ./mathfield.module
Afterbuild callbcak for forms with math expression fields.
_mathfield_evaluate_element in ./mathfield.module
Helper to evaluate a single mathfield element.

File

./mathfield.module, line 460
Adds a dynamic math expression field.

Code

function mathfield_evaluate($expression, $settings, $replacements = array()) {

  // Add replacements.
  if (!empty($replacements)) {
    foreach ($replacements as $token => $value) {
      if (!is_numeric($value)) {
        return FALSE;
      }
      $expression = str_replace($token, floatval($value), $expression);
    }
  }
  module_load_include('inc', 'mathfield', 'includes/mathfield.math_expr');
  $result = FALSE;
  $expressions = explode(';', $expression);
  $math = new MathfieldMathExpr();
  try {
    foreach ($expressions as $expr) {
      if ($expr !== '') {
        $result = $math
          ->evaluate($expr);
      }
    }
  } catch (MathfieldException $e) {
    watchdog('mathfield', 'Could not evaluate math expression %expression. Error: @message', array(
      '%expression' => $expression,
      '@message' => $e
        ->getMessage(),
    ), WATCHDOG_WARNING);
    drupal_set_message(t('Math error: Could not evaluate math expression %expression.', array(
      '%expression' => $expression,
    )), 'warning');
  }
  if ($result !== FALSE) {
    return number_format($result, floatval($settings['scale']), $settings['decimal_separator'], '');
  }
  return FALSE;
}