VN:F [1.9.11_1134]
Rating: 3.0/5 (2 votes cast)

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 MSSQL database to a double. The following code would always report an error:

NOTE FROM THE AUTHOR, RORY HANSEN
Have you found this post helpful?
If so, I'd appreciate if you could indicate so by pressing the Google Plus button below.

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.)

VN:F [1.9.11_1134]
Rating: 3.0/5 (2 votes cast)
Casting from MSSQL money to C# double, 3.0 out of 5 based on 2 ratings

Related posts:

  1. Using JavaScript to validate one or more grouped checkboxes
  2. Using IFRAME in ASP.NET
  3. Firefox 3.0 is out, possible to make money? We’ll find out…
  4. Update on Text-Link-Ads: Over $70 per month, no work

8 Comments to “Casting from MSSQL money to C# double”

  • 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

  • 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

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

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

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

  • erik… you’re awesome. That worked for me. Not sure why money is 4 decimals long in SQL fields but thanks to you, I was able to convert my money field in SQL to a correctly US formated two decimal places. Thanks. Dale n Orlando, Florida

  • Thanks a lot, you saved me from a headache !

  • Who do you work for?

Post comment