Simple answer is that computers use binary arithmetic. It’s fine for integers but when it comes to floating point numbers, the answers aren’t always exact. You just need to round the number to 2 places of decimals.
I mean… it still doesnt actually solve Pitfall 3 that she outlined in her post…
and OP’s post is almost already following the strategy. take the float value of the string with no monetary separators is equivilant to treating the amount as a whole number of cents, because that regex will strip out the cents separator. As far as I can see, the assumption is that all currency amounts are in euros, so the idea of currency unit/conversion is irrelevant.
sum your expenses using the whole numbers, then divide the total by 100 and round to 2 decimal places.
Hi @m_hutley thanks for your help. I’ve got another question. I’m using a mask plugin to make sure the values are formatted in the right way for example 1,234.34 then as you saw I remove the comma and leave the dot for the cents. Now what is the best way to store these values in the mysql database? Shall I use the format decimal and leave the dot for cents or is it better to remove the dot as well, store the value as number and then do maths after? Many thanks
With money I’d recommend storing things in integers and keep them integers as long as possible, i.e., only format as price at the last possible moment in templates. Sure, the database supports fixed precision, but when you read it back from the database it’s a float again in PHP. And floats are a royal PITA to work with.