Florjon
Florjon

Reputation: 3619

Math calculation with decimal isn't correct

I have a C# method and which accepts three string parameters. After converting them to decimal, I am trying to perform a simple math calculation. I don't understand, why isn't the result correct?

decimal d = MyFunction(x, y, z);


public decimal MyFunction(string x, string y, string z)
{
    decimal dx = 0;
    decimal dy = 0;
    decimal dz = 0;

    Decimal.TryParse(x, out dx);
    Decimal.TryParse(y, out dy);
    Decimal.TryParse(z, out dz);

    decimal result = dx - dz + dy;
    return result;
 }

Thanks in advance.

Upvotes: 1

Views: 3884

Answers (4)

SLaks
SLaks

Reputation: 887305

If the result you're getting is zero, then it could be that TryParse couldn't parse the strings.

You should replace the calls to TryParse with decimal dx = Decimal.Parse(x); and see if it throws an exception.

If that isn't the problem, we cannot help you until you provide more details.

What are x, y, and z equal to, and what is the result you're getting?

EDIT: In response to the additional information added to the question, it appears that everyone else is correct and the problem is probably the lack of parenthesis.

Upvotes: 4

Joren
Joren

Reputation: 14746

Edit in response to more question information:
I don't see your problem. I get 151804.25, which is the correct result of doing (1186197.29 - 1260711.19) + 226318.15.

Maybe you're confused because you expect x - z + y to mean x - (z + y) and not (x - z) + y?
C# operator precedence for - and + is left to right, so it means (x - z) + y. If you want x - (z + y), you will have to write it that way.


Floating point calculations are often fundamentally inexact (although decimal does a lot better than float and double for monetary and similar usage). Example:

decimal x = 1m / 3m;
decimal y = 0;

for (int i = 0; i < 1e6; i++)
{
    y += x;
}

Result of y:

333333.33333333333333333072026

Upvotes: 6

Dan Tao
Dan Tao

Reputation: 128317

I have done this calculation (1186197.29 - 1260711.19 + 226318.15) three times over now, and I am getting 151804.25.

The M at the end of the number just means it's a Decimal, by the way.

Upvotes: 2

MusiGenesis
MusiGenesis

Reputation: 75296

I think I see what your problem is. This function is working correctly, but look closely at this line:

decimal result = dx - dz + dy;

You may have intended to write this:

decimal result = dx + dz + dy;

or this:

decimal result = dx - (dz + dy);

Upvotes: 2

Related Questions