1

Note: I'm already using decimal.Decimal

What is the best way to perform and display calculations to the end user when you are required to output in the following rough style:

Item - £ 70.10 
Item - £  5.67
Item - £ 10.33

--------------
Total  £ 86.10

I was always taught in maths as a kid to not round before your final answer, else you'll lose precision, but in this case if you don't it looks like we have calculation errors. as the calculation behind the display is not the same as the user would do from the numbers displayed to them.

EG:

My app will be doing: 70.1034 + 5.6693 + 10.333333333 = 86.1060333 (86.11 2dp)

My end user will be doing as above: 70.10 + 5.67 + 10.33 = 86.10

Therefore i appear to be incorrect. What is the best way to overcome this? (I mean generally, but python specific methods will help too)

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Jharwood
  • 1,046
  • 2
  • 11
  • 28
  • SO has got you covered: http://stackoverflow.com/questions/455612/python-limiting-floats-to-two-decimal-points – Talvalin Oct 17 '12 at 16:33

1 Answers1

3

Use the decimal module to get math that works out correctly. You can set it so each value will automatically use two decimal places.

>>> decimal.getcontext().prec = 2
>>> decimal.Decimal(1)/decimal.Decimal(3)
Decimal('0.33')

When you're working with money, it's normal to lose precision at each intermediate calculation.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • so you're saying that losing half penny amounts doesn't matter? what if i sold individual screws (like an ironmongery) where there were 5000 screws per box, and the box cost me £10, so each screw costs £0.002, now i still want to charge for them, as i sell them in bunches that the customer needs (eg 56 screws) how would that be overcome? – Jharwood Oct 17 '12 at 20:45
  • 1
    @Jharwood, if the amounts you're working with are small then you should add a couple of decimal places and display *all* of them to the user. – Mark Ransom Oct 17 '12 at 20:49
  • unfortunately i have to display to 2 decimal places – Jharwood Oct 25 '12 at 09:45
  • @Jharwood then you are stuck. You can charge £0.01 per screw or £0.02 per 10. The constraints of your problem are preventing you from making the optimal choice. – Mark Ransom Oct 25 '12 at 12:50