title: C# Decimal type rounding off inappropriately
body: <p>I've got an in house banking solution for a summer camp that I'm a part of. The issue is coming up that some accounts are exactly a penny off at the end of the season.</p>
  
  <p>I'm using SQL Server Express, with two tables. One table with all accounts, which holds their current balance. The other table is a running transaction log. The idea is that if I were to sum up all the transactions in the log, it should equal the current account balance for any given account.</p>
  
  <p>But it doesn't. For example, I sum the database and see that a given account should have <code>$15.10</code>, but the account table shows that they have a balance of <code>$15.09</code></p>
  
  <p>Here is the relevant code:</p>
  
  <pre><code>//Amount is negative, they bought something
  if (amount &lt;= 0)
  {
      //Check if they have enough money to buy, or they are a paid account type (faculty, staff)
  
      if (account.Balance &gt;= Math.Abs(amount) || account.AccountType &gt; AccountType.Camper)
          account.Balance -= Math.Abs(amount);
      else
          return Error.LowBalance;
  }
  else
  {
      account.Balance += Math.Abs(amount);
  }
  
  var t = new Transaction
  {
      AccountId = account.Id,
      Amount = amount,
      SubmittedBy = username,
      TransactionRefId = refId,
      ComputerHostname = hostname,
      Location = location,
      Notes = notes
  };
  
  _db.Transactions.Add(t);
  _db.SaveChanges();
  </code></pre>
  
  <p>I'm using Entity Framework, code-first. The datatype for <code>Account.Balance</code>, <code>amount</code>, and <code>Transaction.Amount</code> are all <code>System.Decimal</code></p>
  
  <p>I don't understand why there is a rounding error, I'm using all the proper datatypes for this situation. The usual way that I see this is when they have two different transactions for <code>$0.75</code>. For some reason the code is saying <code>0.05 + 0.05 = 0.09</code></p>
  
  <p>In my database, the <code>Accounts.Balance</code> column datatype is <code>decimal(18,2)</code></p>
  
  <p>I understand that floating point numbers can do this sometime, but I'm looking for a fix. I thought I was covered by using the <code>System.Decimal</code> datatype.</p>