Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

boolean expression with decimals #108

Open
jpoorrandp opened this issue Dec 5, 2023 · 1 comment
Open

boolean expression with decimals #108

jpoorrandp opened this issue Dec 5, 2023 · 1 comment

Comments

@jpoorrandp
Copy link

Is it possible to use decimal type in a boolean expression such as:: "myDecVar >= 10.0" ?

If MyDecVar is something like 3.1, flee throws an error, saying:

"Error: CompareElement: Operation 'GreaterThanOrEqual' is not defined for types 'Decimal' and 'Double'"

Same for GreaterThan and Equals.

Works fine with integers.
Is there a way to use decimals this way in flee, or should I just convert to decimals.
Thanks
Jonathan

@silvairsoares
Copy link

silvairsoares commented Sep 10, 2024

For this type of operation, you may need to configure the locale of the expression resolver.

Here I did something like this:

using Flee.PublicTypes;

public class DynamicExpressions
{
	private readonly ExpressionContext expressionContext = new();

	public DynamicExpressions()
	{
		// Inclusion of System.Math, to allow the use of all its methods
		expressionContext.Imports.AddType(typeof(Math), "Math");

		// Regionality settings
		expressionContext.ParserOptions.DecimalSeparator = '.';
		expressionContext.ParserOptions.FunctionArgumentSeparator = ',';
		expressionContext.ParserOptions.RecreateParser();
	}

	/// <summary>
	/// Receives a boolean expression in string format and returns the result
	/// <Examples: "(10.90 - 5.0 < 0.0)", "("123" <> "")"
	/// </summary>
	/// <param name="expression"></param>
	/// <returns></returns>
	public bool EvaluateBoolExpression(string expression)
	{
		bool result;
		try
		{
			IGenericExpression<bool> e = expressionContext.CompileGeneric<bool>(expression);
			result = e.Evaluate();
		}
		catch (Exception ex)
		{
			throw new Exception("Erro ao validar a expressão booleana: (" + expression + ") - '" + ex.Message + "'");
		}
		return result;
	}

	// Example of using a System.Math method
	// double valorArredondado = expressionContext.CompileGeneric<double>("Math.Round(1.55540040, 2)").Evaluate();
	public double EvaluateDoubleExpression(string expression)
	{
		double result;

		try
			IGenericExpression<double> e = expressionContext.CompileGeneric<double>(expression);
			result = e.Evaluate();
		}
		catch (Exception ex)
		{
			throw new Exception("Error validating mathematical expression: (" + expression + ") - '" + ex.Message + "'");
		}
		return result;
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants