C# percent calculation with decimal type causes problems

decimal hundred = 100;
decimal value = 5000;
decimal sum = 1100000;

decimal valuePercentOfSum = value / sum * hundred;        //result = 0.4545454545454545454545454500M
decimal percentOfSum = sum / hundred * valuePercentOfSum; //result = 4999.9999999999999999999999500M

I would expect the result of percentOfSum to be the original value of value (5000)

I need a way to do calculations like this back and forth, and I can simply not do ANY rounding.

Any help?

Upvotes: 5

Views: 478

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

Someone has to Round (whether you like it or not), as you're dealing with Irrational Numbers and/or Numeric Types with a limited precision

If you use double it will Round for you, if you use decimal it has more precision. However, you will have to live with the fact it leaves the precision it has.

Depending on what you want to do, a decimal might be less convenient, though if you understand the ramifications for both Types (and that there is no free lunch), you can choose accordingly.

Upvotes: 8

M Stoerzel
M Stoerzel

Reputation: 300

If you use double instead of decimal you should get better results.

double hundred = 100;
double value = 5000;
double sum = 1100000;

double valuePercentOfSum = value / sum * hundred; 
double percentOfSum = sum / hundred * valuePercentOfSum; // result = 5000

Upvotes: 1

Related Questions