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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With