Friday, 14 June 2013

Working with percentages

I wouldn't say that I'm the best mathematician; if I'm being generous, my skills in the maths department is somewhere about average which isn't always a good place to be for a programmer. But what I lack here I make up for in understanding of how computers work and how to program them, and this is what acts as a stabiliser against the wrath of BODMAS and such like.

So, I've been working on a project for a client which in part has to work out percentages of a price, like adding VAT levied by the Government on saleable goods. Now, this is actually the easy bit. VAT, at the time of writing, is 20%, so if an item costs £100 without it, that item will be £120 including VAT. So, writing the code for this is simple: take the current price, work out 20% and add that to it. Or, multiply the current price by 1.20, which does the same thing.

Writing the code for this is easy, in a C-like language, it would be something like:

Great! Assuming the VAT rate will always be 20%, this will always work. But not long ago, VAT was at 17.5%, and before that, which dropped temporarily to 15%. Now, let's say that you want to work with different percentage rates, or the rate unexpectedly changes. Something like the following will work:

Things should be fairly self-explanatory here. This example means that if your tax rate changes, you only have to change one variable rather than tracing all of the instances of *1.20f in your source code. This makes it easy to set percentage rates for other taxes, levies or fees that a client may encounter. The only problem now is what to do with the third decimal place, say if something works out to be £17.8555 with fees or taxes added? I think things are usually rounded up though.
Note that the £ sign doesn't appear on my computer here - all of the documentation online says that it should be 0xa3 (or 163 in human), but I found it to be 156 (or 0x9c in hexadecimal) on this Windows 7 machine.