Home > OS >  Use DataTable Compute method for a different locale?
Use DataTable Compute method for a different locale?

Time:02-08

I'm using the Compute method to evaluate an expression. My current locale is de-DE. This is simply done by:

var dt = new DataTable() {
    Locale = CultureInfo.CurrentCulture,
};

var v = dt.Compute(myExpression);

When I enter an expression such as:

30.5 / 2.25

The expression is evaluated correctly.

However, when as my locale is different, I need to enter the above expression as:

30,5 / 2,25

The expression is not evaluated as expected.

How do I get the Compute method to evaluate expression correctly for the given locale?

CodePudding user response:

I'm afraid setting Locale doesn't help:

In columns that contain expressions, the InvariantCulture is used. The CurrentCulture is ignored.

So maybe you have to rethink your design. Why ...

when my locale is different, I need to enter the above expression as: 30,5 / 2,25

Couldn't you always use InvariantCulture to generate the expression? If this expression is entered by the user, you might want to provide multiple TextBoxes for the numbers and a DropDownList for the operator. Then you can easily parse the values and create the expression correctly with InvariantCulture.

CodePudding user response:

Easy, crude workaround that works:

var dt = new DataTable();

var temp = myExpression.Replace(".", string.Empty).Replace(",", ".");
var v = dt.Compute(temp, string.Empty);

Won't work when changing locales. Might be expanded to handle locales.

  •  Tags:  
  • Related