• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1207
  • Last Modified:

C# - how to add decimal types together

Simple question.   How can I add 2 decimal data types together?

string x;
decimal y;
decimal w;
     while (dtrResults1.Read())
            {
             x = dtrResults1.GetString(0);
             w = Decimal.Parse(x);
             y = y + w;
            }

I get an error message with the code above.  
0
Hojoformo
Asked:
Hojoformo
  • 3
1 Solution
 
COBOLdinosaurCommented:
What language? Where? server? client?

What is the error you get?

Cd&
0
 
KeirGordonCommented:
I think decimal is not a basic datatype and must be instantiated.  I assume you are getting a null reference exception.  Instatiate y.

string x;
decimal y = new decimal(0);
decimal w;
     while (dtrResults1.Read())
            {
             x = dtrResults1.GetString(0);
             w = Decimal.Parse(x);
             y = y + w;
            }
0
 
KeirGordonCommented:
Also, probably some code like this is much more efficient..... Should do the same thing as yours.

double y = 0;
while (dtrResults1.Read())
     y += dtrResults1.GetDouble(0);
         
0
 
KeirGordonCommented:
Or better yet.... if thats a datareader, and your just adding up the values anyway.... why didnt you just use a sum() aggregate function in your sql query and do an executeScaler rather than executeReader...... that'd be alot prettier.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now