Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算十进制表达式时,DataTable.Compute失败_C#_Datatables_Evaluation - Fatal编程技术网

C# 计算十进制表达式时,DataTable.Compute失败

C# 计算十进制表达式时,DataTable.Compute失败,c#,datatables,evaluation,C#,Datatables,Evaluation,我正在使用DataTable类的计算方法来计算和表达式。 当值为整数时,计算有效;当表达式为十进制值时,计算失败。我得到一个“System.FormatException”异常 以下是示例代码: var dt = new DataTable(); var passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null); //works var failingResult = dt.Compute("CON

我正在使用DataTable类的计算方法来计算和表达式。 当值为整数时,计算有效;当表达式为十进制值时,计算失败。我得到一个“System.FormatException”异常

以下是示例代码:

var dt = new DataTable();
var passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null);   //works
var failingResult = dt.Compute("CONVERT('100.1', 'System.Decimal') > 3", null); //fails

起初我无法重现您的问题,但后来使用此代码

Thread.CurrentThread.CurrentCulture = new CultureInfo("af-ZA");
var dt = new DataTable();
var passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null);   //works
var failingResult = dt.Compute("CONVERT('100.1', 'System.Decimal') > 3", null); //fails
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var dt = new DataTable();
passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null);   //works
failingResult = dt.Compute("CONVERT('100.1', 'System.Decimal') > 3", null); //fails
我得到了相同的格式错误,所以这是一个文化信息应用到您的代码的问题。我可以用这个代码解决它

Thread.CurrentThread.CurrentCulture = new CultureInfo("af-ZA");
var dt = new DataTable();
var passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null);   //works
var failingResult = dt.Compute("CONVERT('100.1', 'System.Decimal') > 3", null); //fails
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var dt = new DataTable();
passingResult = dt.Compute("CONVERT('100', 'System.Decimal') > 3", null);   //works
failingResult = dt.Compute("CONVERT('100.1', 'System.Decimal') > 3", null); //fails
不确定这是否是解决此问题的最佳方法,因为表使用后的代码可能会出现问题,而且我非常确定,在进行此更改后,您需要将CultureInfo重置为原始的CultureInfo

让我们看看其他人是否有更好的解决方法。

根据:

没有科学记数法但带有小数点的实文字被视为System.decimal。如果数字超过System.Decimal支持的最大值或最小值,则将其解析为System.Double。例如:

142526.144524将转换为十进制

345262.78036719560925667将被视为双倍


因此,只需使用
dt.Compute(“100.1>3”,null)
就可以了。

如果我运行代码,两者都可以正常工作,两者都必须正常工作。。。。!!由于某种原因,当我有单引号时,它在我这边失败了。我删除了数字周围的引号,现在可以了。谢谢@taffer。当区域性更改时(例如从一个环境移动到另一个环境时),这不会导致问题吗?不会,因为这些是数字文字。只有在使用字符串转换时才会出现问题。谢谢@Steve。这正是问题的根源。它正在使用当前线程的区域性。事实证明,在南非,小数点分隔符是逗号而不是句号。