Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 587
Simon Sondrup Kristensen Avatar asked Mar 08 '18 10:03

Simon Sondrup Kristensen


2 Answers

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.

like image 137
TheGeneral Avatar answered Sep 25 '22 17:09

TheGeneral


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
like image 41
M Stoerzel Avatar answered Sep 24 '22 17:09

M Stoerzel