Mixing Decimal and Double

Run into this quite a lot

Operator ‘+’ cannot be applied to operands of type ‘decimal’ and 'double’

I always mange to hack my way through it. But what’s the proper method for expressions that mix decimals and doubles?

The “programming environment” is the expression builder in the configurator rules.

The exact expression is

JobMtl.QtyPer = (Round(((Inputs.P01_Dec_ActiveLength.Value + 9.9) / 20) ,0) + 1) * 0.06 / 51;

Where input Inputs.P01_Dec_ActiveLength.Value is a decimal.


The expression I end up with is
JobMtl.QtyPer = System.Convert.ToDecimal ((System.Math.Round(((System.Convert.ToDouble(Inputs.P01_Dec_ActiveLength.Value) + 9.9) / 20) ,0) + 1) * 0.06 / 51);

Not an expert, but I think you’re doing the right thing by explicitly converting your decimal to double before adding the 9.9. Any literal in C# with a decimal point is inferred as a double unless a suffix is added, so while 9.9 looks like a decimal to us, it’s actually a double.
Remember that Math.Round returns a double and consumes a double.

Unless precision if your goal, double should be fine.

Is the precision of a ‘decimal’ universal? (I mean like how IEEE standards exist for float and doubles). If so, to how many places?

Or is it dynamic based on the system setup? If I have the company configured to use 4 decimals places, does that mean that 0.0001 is the smallest resolution for a value of type decimal?

What dothe following statements return?

0 or 0.0001?  

0 or 0.0001?

A little test can be done in Visual Studio to help answer your questions.

  static void Main(string[] args)
            while (true)
                decimal test1 = System.Convert.ToDecimal(0.00005);


                decimal test2 = System.Convert.ToDecimal(0.00009);

                var test3 = 0.00005D;

                var test4 = 0.00009M;

                var test5 = 1.04D + 9.9D;

                var test6 = 1.04M + 9.9M;



Not sure if that helps with your question but you could play around with it to see at least what the compiler is doing.

Also, decimal in C# can represent 29-29 significant figures, whereas a double can represent 15-16. Either is probably more than enough, especially with non=scientific calculations like you’re doing.

1 Like