Calculating C # percent 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 expect the result to percentOfSumbe the original value (5000)

I need a way to do calculations like this back and forth, and I just can't do ANY rounding.

Any help?

+4
source share
2 answers

Someone should round (like it or not), since you are dealing with Irrational Numbers and / or numeric types with limited precision

If you use double, Round will be for you, if you use decimal, it has higher accuracy. However, you will have to live with the fact that it leaves the accuracy that it has.

, , decimal , ( ), .

+8

double , .

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

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

Source: https://habr.com/ru/post/1694638/


All Articles