INCLUDE_DATA

Article written

  • on 21.06.2005
  • at 08:02 AM
  • by Rory

Casting from MS SQL money to C# double 5

Jun21

I’m just beginning to transition to ASP.NET and C# from a largely Java / C++ / C background, and along the way, I’m finding myself often stumped with what seems like really simple problems.

For example, today, when writing a ASP.NET web service in C#, I had trouble casting a money value retrieved from a MS SQL database to a double. The following code would always report an error:

C#
double cost;
cost = (double) dr["cost"];

I also tried using a float, but that didn’t fix the problem either.

The _correct_ type to use in this case is actually Decimal, and I learned this only after a co-worker sent me a link to a document on the MSDN site that has a table showing all of the proper type conversions from one system to another. So, this code _does_ work:

C#
Decimal cost;
cost = (Decimal) dr["cost"];

You can find the table here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconusingparameterswithdataadapters.asp

(Scroll about halfway down; you can’t miss it.)

subscribe to comments RSS

There are 5 comments for this post

  1. Satish says:

    I hv some problem in money data type of MSSQL i wt to when to use that data type and my problem is if i insert 12.58 then i wt when ever i retrive data i wt same figur not 12.5800 or something else

    Replay Soon

  2. Aditya Kumar says:

    I hv some problem in money data type of MSSQL i wt to when to use that data type and my problem is if i insert 12.58 then i wt when ever i retrive data i wt same figur not 12.5800 or something else

  3. filip says:

    Use double for value
    for sqldbtype use float
    in database
    use money

  4. erik says:

    You need to change (double) dr["cost"]; to Convert.ToDouble(dr["cost"];

  5. erik says:

    oops should be this Convert.ToDouble(dr["cost"]);

Please, feel free to post your own comment

* these are required fields