How to evaluate a string expression in C# which can divide by zero?

1.4k Views Asked by At

I am facing an odd problem in C#, where I need to evaluate some mathematical string expressions, which may divide by 0. Here is an example:

string expression = GetUserInput(); // Example: "(x + y) / z", where z may equal to 0

I am currently using NCalc library for evaluating this expression, which throws a DivideByZeroException if the z argument in current expression is 0.

I tried catching the exception by doing:

try {
    string formula = GetUserInput();
    Expression exp = new Expression(formula);

    // ...

    exp.Evaluate(); // Throws a DivideByZeroException

} catch (DivideByZeroException e) {
    //ignored
}

However, I need to evaluate this expression more than 6000 times (with different variables) in a time-efficient manner, so catching an exception every time significantly slows down my application.

I have multiple such expressions, each of which is entered by a user. I can not know if a given expression attempts to divide by zero or not.

Is there a way to evaluate a mathematical expression in C# in a "safe" way, where attempting to divide by 0 will return a static number (0, or infinity), without throwing an exception?

2

There are 2 best solutions below

0
Keith Nicholas On BEST ANSWER

try making your values floating point.

Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero. Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic. Because the following example uses floating-point division rather than integer division, the operation does not throw a DivideByZeroException exception.

https://msdn.microsoft.com/en-us/library/system.dividebyzeroexception.aspx

2
anil On

Evaluate z. If z is > 0 then do the operation, else move to next evaluation.