5
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?

TheGeneral
  • 79,002
  • 9
  • 103
  • 141

2 Answers2

8

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.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Really sad to hear this, becuase I dislike using double here since that has caused other problems for me earlier, such as 0.1 + 0.2 = 0.300000004 – Simon Sondrup Kristensen Mar 08 '18 at 10:58
  • @SimonSondrupKristensen unfortunately for ultimate accuracy and convenience, you have to trade something. It really depends on what you want to do and why to determine which might be the best approach and most convenient . – TheGeneral Mar 08 '18 at 11:03
1

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
M Stoerzel
  • 300
  • 1
  • 13