Thursday, 14 June 2012

Looking after the pennies

A piece of advice which I was given by an accountant friend is to store the money as an integer, i.e. in cent, or pence, depending on your currency. Why? Because, computers are imprecise he said... Nonsense!

Take this example:
When I was young I got 10p every Sunday as pocket money - I could do with this what I wanted, the shopkeeper invariably got it! But if I wanted to get a Beano comic, I'd have to be disciplined and save up to £1 - ten weeks of torture*.  Pythonically, this arrangement can be expressed as:

allowance = 0.1
saving = 0.0
for weeks in range(10): saving += allowance

This should give me my £1, right? Every week, my savings are increasing by £0.10p after all.


It looks like I would have to save for an extra week to get my Beano.  What happened? A computer cannot precisely represent 0.1 in binary, at least not in a finite amount of memory because in binary it is 0.000110011001100... As a result, the computer stores an approximation of 0.1 for my allowance, but the error builds and becomes more significant with successive operations.

Scaled up in a real-world scenario with many multiples of transactions, this would an accountant crazy. You simply cannot have money go missing.  The advice I received was to work in pennies and divide by 100 whenever you need to display the amount.


* I have no idea how much the Beano cost back then.


Similarly, I noticed on the package in which my Raspberry Pi was shipped this telephone number which reminded me to post about storing data in an appropriate format in a database.



Telephone numbers should be stored as a string - you are never going to be doing sums with telephone numbers are you?


No comments:

Post a Comment