2017-04-17 81 views
0

我想转换字符串来执行算术表达式,但获取格式表达式。我想要表达式被计算和最终答案。如何将字符串转换为十进制表达式?

// original value 
    string text = @"4'-8"x5/16"x20'-8 13/16"; 

       string path = text.Replace("'", "*12").Replace("-", "+").Replace("x", "+").Replace(" ", "+").Replace(@"""", ""); 
       System.Console.WriteLine("The original string: '{0}'", text); 
       System.Console.WriteLine("The final string: '{0}'", path); 

        Console.WriteLine(); 

        decimal d = decimal.Parse(path, CultureInfo.InvariantCulture); 
        Console.WriteLine(d.ToString(CultureInfo.InvariantCulture)); 

// after converting got this value in debug 
//'4*12+8+5/16+20*12+8+13/16' 
+0

什么是确切的例外和你在哪一行得到它 – Sybren

+0

使用'decimal.Parse'不会计算存储在字符串中的数学表达式。它不这样工作。你将不得不提取操作数并在你的代码中进行数学运算。 –

+0

十进制d = decimal.Parse(path,CultureInfo.InvariantCulture); –

回答

3

您可以使用DataTable类评估的数学表达式的字符串,使用计算()方法,传递的String.Empty作为第二个参数。

var parsingEngine = new DataTable(); //in System.Data 
int i = (int)parsingEngine.Compute("3 + 4", String.Empty); 
decimal d = (decimal)parsingEngine.Compute("3.45 * 76.9/3", String.Empty); 

要知道,计算返回一个对象,你必须小心地将它转换为基于数学表达式应该产生什么样的合适的类型。

+0

出错:指定的转换无效。 var parsedvalue = new DataTable(); int i =(int)parsedvalue.Compute(path,String.Empty);十进制d =(十进制)parsedvalue.Compute(path,String.Empty); –

+0

就像我说过的,铸造可能很困难,因为Compute会根据数据选择类型。它肯定会是整数,双精度或小数。您可以使用“is”或GetType()来动态确定类型。例如,对象o = parsingEngine.Compute(myexprSTR,String,Empty);如果(o是int)强制转换为int;否则如果(o是十进制)转换为十进制;否则如果(o是双精度)投射为双精度;等等。 使用具有适当支持符号的表达式也是很重要的,例如'*'不是'x','/'不是'÷'等等。您不能使用任何可能数学的字符串,您必须使用符合传统的一个子集。 – schulmaster

+0

如果这仍然不起作用,只需打印GetType()的返回值,它会通知您Compute编码的内容。另外,我的答案中的两个表达式以及他们的演员都是有效的例子,可以帮助您指出正确的方向。 – schulmaster

0

不幸的是,.NET没有内置任何内置函数来评估数学表达式字符串。您需要使用第三方库,如NCalc

然后你就可以在你的代码中使用它像这样

// original value 
//string text = System.IO.File.ReadAllText(@"4'-8"x5/16"x20'-8 13/16"); This needs to be a filepath. 
string text = @"4'-8x5/16x20'-8 13/16"; 

string path = text.Replace("'", "*12").Replace("-", "+").Replace("x", "+").Replace(" ", "+").Replace(@"""", ""); 
System.Console.WriteLine("The original string: '{0}'", text); 
System.Console.WriteLine("The final string: '{0}'", path); 

Expression e = new Expression(path) 
Console.WriteLine(e.Evaluate); 
+0

您将代码保留在原来的位置 –

+0

另外'File.ReadAllText'需要一个文件路径...它是考虑OP的数学表达式 –

+0

我删除了引发表达式的部分我从OP的答案中遗漏了不正确的'File.ReadAllText'因为我假设他或她将这些内容呈现给我们展示预期文本输入的示例。即使它的格式不正确.... –

相关问题