c# - decimal rounding issues for exact VAT calculation -


is there more professional way of rendering below long-winded, convoluted attempt extract net values , establish vat amount equal starting total (tot1)

            decimal tot1 = convert.todecimal(typea) + convert.todecimal(typeb);             decimal nettot = math.round(convert.todecimal(tot1) / 1.2m, 2);             decimal vat = tot1 - nettot;             decimal neta = math.round(convert.todecimal(typea) / 1.2m, 2);             decimal netb = math.round(convert.todecimal(typeb) / 1.2m, 2);             decimal netaa = nettot - (neta + netb);             decimal netaaa = netaa + neta; 

having said that, code works in 9 out of 10 cases. there plus or minus 0.01 difference , don't understand why

stop rounding in middle of operation , round final numbers got. problem getting when numbers 0.333333 , round before continuing math, in example, throw away 1/3 of cent.

alright, here's example, lets suppose reason these values:

typea = 39.5 typeb = 0.5 

it sums 40. nettot ((typea + typeb)/1.2) be:

33,333333333333333333333333333333 

after that, round 33.33. then, neta (typea/1.2) , netb (typeb/1.2) be:

neta = 32,916666666666666666666666666667 netb = 0,41666666666666666666666666666667 

you rounded each 32.92 , 0.42 respectively, sums 33,34, unlike nettot got rounded 33.33.

as can see, sum of neta , netb after rounded screws math.


Comments