PHP Money Library – safe money calculations

The basic question is: why should we use this type of library and why not use the float type instead? The problem is that computers are not able (and have never been) to handle floating point values with real accuracy. While for some insignificant data this should not be a problem, in the case of recalculating the amounts of money-related transactions, it is already a serious concern. This library frees us from issues related to currency operations, storing them (or just preparing for it), adding or converting. All this without fear about lack of precision.

The explanation of the problem with floating point numbers and their accuracy is described in IEEE 754 standard. In short: types such as float are not suitable for performing floating point operations (such as adding, subtracting, multiplying, dividing). As a consequence, they are also not suitable for operations on financial values – because in such cases the problems with inaccuracies can lead to erroneous and unexpected results! For Java, we have the BigDecimal type, and for PHP we should use additional libraries created to solve this problem. Money is one of them.

Of course, the purpose of the entry is not to describe all available Money library functions. Let us focus only on the most important aspects. First of all, thanks to Money we can store your financial values as strings. This library is also able to handle very large numbers with no problem, so even transactions in billions of dollars are not a problem here. This is also convenient currency handling and their optional conversion if you need to use such operations. An example of basic using Money from official documentation:

There is no problem with the most important operation:

Other options are: formatting (using Intl extension), aggregations amounts (based on ratios or by targets), BitCoin parser, exchange and much more.

With Money we can not use float to store and operate on financial data, we can do this in safe way. With this small library, all data is clear, reliable but there are also some very useful tools for formatting and converting amounts.

Leave a Reply