This part of code should speak for itself, my question is can I get 1242.08 result in res variable, and not 1242.07, because in math
b = 1/(1/b) and in double which has less precision it seems I got good result
Can I fix decimal part of calculation to give me mathematically right result:
decimal rate = 124.2075M; decimal amount = 10M; decimal control = decimal.Round(rate * amount, 2); //it is 1242.08 //but decimal res = decimal.Round(amount * (1 / (1 / rate)), 2);//1242.07 - should be 1242.08 decimal res1 = decimal.Round(amount * 124.2075M, 2);//1242.08 OK ///////////////////////////////////////////////////////////// //while with double seems OK double ratef = 124.2075; double amountf = 10; double resf = Math.Round(amountf * (1 / (1 / ratef)), 2);//1242.08 OK double res1f = Math.Round(amountf * 124.2075, 2);//1242.08 OK
b = 1/(1/b)which is good in pure math (for non-zerob), simply does not hold for floating-point arithmetic. In particular, whenrateis124.2075M, then1M / (1M / rate)is something else, namely124.20749999999999999999999991M. The good thing aboutdecimalis that you can clearly see from the printed representation of the value, that it is not the same. (Fordoubleandfloat, sometimes there is "hidden" precision unless you use a special format string for printing the value.)