Operator '+' can not be applied to operands of types 'decimal' and 'double' - NCalc

0

I'm using the NCalc lib

A simple formula like "Abs (-1) + Cos (2)" gives the following exception:

  

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

Why? How to solve?

The calculation is to be executed as follows:

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

The only discussion related on the project site is a little old and talks about editing the source code link

    
asked by anonymous 25.03.2015 / 14:21

3 answers

1

There is no problem with the NCalc lib, the point is that one method returns Decimal and the other returns Double. The .NET compiler does not allow operations between these two object types because the precision of the two are very different.

The correct one is to convert the result of one of the methods to the data type of the other method.

using System;

public class Program
{
    public static void Main()
    {
        double dbl = 1;
        decimal dec = 2;

        // Neste exemplo converti o valor double para decimal.
        var result = Convert.ToDecimal(dbl) + dec;

        Console.WriteLine(result);

        // Esta operação retorna a exceção Operator '+' can'tbe applied to operands of types 'decimal' and 'double'
        Console.WriteLine(dbl + dec);
    }
}
    
25.03.2015 / 18:30
1

There is a problem with the NCalc lib that is already fixed in the source code.

link

This review is not available as a binary.

    
25.03.2015 / 18:46
0
using System;

class Program
{
  public void Main()
  {
    double a  = 1;
    decimal b = 2;
    a = Convert.ToDouble(1);
    b = Convert.ToDouble(2);

    int valor = a + b;

    Console.Write(int.ToString());

    return 0;
  }
}
    
02.05.2015 / 07:02