Trick to fix gst rounding issue -- why does it work?

108 Views Asked by At

In our system, we store prices ex-gst (without gst) and not inc-gst (with gst).The gst in my country is 10%.

For example, if a product has an inc-gst price of $9.95, we store it as $9.05. The $9.05 is calculated like this: $9.95/1.1 = $9.04545454545. We then round-up 9.04545454545 to 2 decimal places, to get $9.05.

The problem is, when we want put the gst back into the price, it doesn't work: $9.05 * 1.1 = $9.955, which results in $9.96 when we round-up to 2 decimal places.

There is code in my system which apparently fixes this problem, but I don't understand why it works, or if it works in all cases. Here is the pseudo-code

inc_gst_price = round_up_to_2_decimal_places(ex_gst_price*1.1)
inc_gst_price = inc_gst_price * 100

if the last digit of inc_gst_price   == 9
     inc_gst_price +=  1
else if the last digit of inc_gst_price == 4
     inc_gst_price +=  1
else if the last digit of inc_gst_price == 1
     inc_gst_price -= 1
else if the last digit of inc_gst_price == 6
     inc_gst_price -= 1          

inc_gst_price = inc_gst_price / 100

The above code turns $9.96 into $9.95. Which is correct.