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:

use Money\Currency;
use Money\Money;

$fiver = new Money(500, new Currency('USD'));
// or shorter:
$fiver = Money::USD(500);

There is no problem with the most important operation:

$value1 = Money::EUR(800);         // €8.00
$value2 = Money::EUR(500);         // €5.00
$value3 = Money::USD(800);         // $8.00

// Additions
$result = $value1->add($value2);   // €13.00

// Subtractions
$result = $value1->subtract($value2);    // €3.00

// Multiplication
$result = $value1->multiply(2);  // €16.00

// Divisions
$result = $value1->divide(2);    // €4.00

// Comparsions
$result = $value1->isSameCurrency($value3);    // false
$result = $value1->equals($value2);     // false
$result = $value1->greaterThan($value2);    // true
$result = $value1->lessThan($value2);   // false

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.