Operator '+' can't be applied to operands of types 'decimal' and 'double' - NCalc [closed]

不打扰是莪最后的温柔 提交于 2019-12-13 11:18:27

问题


I'm using NCalc to evaluate complex expressions. But I've found a major problem.

A simple formula like new Expression("Abs(-1) + Cos(2)").Evaluate() throws the exception

Operator '+' can't be applied to operands of types 'decimal' and 'double

In C# code Math.Abs(-1) + Math.Cos(2) works, so either I'm doing something wrong or there is a bug in NCalc.

Does anyone have the same problem?

Does anyone have a solution?

The only thread i found on the project's website related to this error is quite old and talks about editing the source code. https://ncalc.codeplex.com/discussions/346702

I also posted a question on their forum but StackOverflow is usualy more dynamic. https://ncalc.codeplex.com/discussions/613634


回答1:


Ok. I looked at the source code. And here is what I found.

The Abs(-1) part of the expression is always evaluated as a decimal

Result = Math.Abs(Convert.ToDecimal(
                        Evaluate(function.Expressions[0]))
                        );

Cos(2) is evaluated as double

Result = Math.Cos(Convert.ToDouble(Evaluate(function.Expressions[0])));

And C# does not allow you to add these two types together.

The reason that Math.Abs(-1) + Math.Cos(2) works is that Math.Abs(-1) actually evaluates as int. And you can perfectly add an int to double.

You can not compile this piece for example (note m for decimal). Math.Abs(-1m) + Math.Cos(2); which is actually what NCalc is trying to do when you type out

new Expression("Abs(-1) + Cos(2)").Evaluate()

I would call this a bug. You can try to edit the source and try to fix this problem or find some other option.




回答2:


After a brief chat with btevfik (helpfull fella) we have come to the conclusion that this is a bug in NCalc. I guess I'll have to analyse the source and fix it.

I still accept answers though...



来源:https://stackoverflow.com/questions/29255487/operator-cant-be-applied-to-operands-of-types-decimal-and-double-ncal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!