2

Since decimal is preferable to double for monetary values (see David's answer here), I am trying to change my code to use decimal instead of double. IOW, I changed this:

public class InventoryItem
{
. . .
    public double UnitCost { get; set; }
    public double UnitList { get; set; }
    public double OpenQty { get; set; }
. . .

...to this:

public class InventoryItem
{
. . .
    public decimal UnitCost { get; set; }
    public decimal UnitList { get; set; }
    public decimal OpenQty { get; set; }
. . .

But that gave me grief in other code, namely "Cannot implicitly convert type 'double' to 'decimal'. An explicit conversion exists (are you missing a cast?)" in this code:

// I changed "double openQty" to "decimal openQty"
decimal openQty = (oleDbD8aReader["open_qty"] is DBNull
                                ? 0.00
                                : Convert.ToDouble(oleDbD8aReader["open_qty"]));

So, I tried changing the "Convert.ToDouble()" to "Convert.ToDecimal()" but that errors out with, "Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and 'decimal'"

The data being retrieved is from MS Access, where the columns under discussion are of type Number and, more specifically, Double (Number.Double, as it were).

How can I coerce/convert Access Double to the "more better" Decimal type?

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Do you have some difficulty in editing the table to Currency data type in MS Access? – Fionnuala Aug 11 '14 at 18:30
  • That's a possibility, but these tables exist on each user's machine, and besides, the code that deals with that is actually in a different (not mine) project altogether. So, converting the data from double to decimal would be far easier. – B. Clay Shannon-B. Crow Raven Aug 11 '14 at 18:33
  • 1
    Your variable openQty is a decimal but you're calling Convert.ToDouble(). You need to call Convert.ToDecimal(), or put a (decimal) at the front of the expression. (decimal)(oleDbD8aReader["open_qty"] is DBNull ? 0.00M : Convert.ToDecimal(oleDbD8aReader["open_qty"])); – Jon Aug 11 '14 at 18:44

1 Answers1

2

The problem was not with the ".ToDecimal()" but with the "0.00"

This:

decimal openQty = (oleDbD8aReader["open_qty"] is DBNull
    ? 0.00
    : Convert.ToDecimal(oleDbD8aReader["open_qty"]));

...had to become this:

decimal openQty = (oleDbD8aReader["open_qty"] is DBNull
    ? 0.00M
    : Convert.ToDecimal(oleDbD8aReader["open_qty"]));

(simply appending the "M" to the "0.00" shut up the compiler critics.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862