TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

Working with Money

If you have worked with money(currency) closely enough, you will know that it is not as easy as it seems. If you have not worked with money a lot, Your first impression might be it is nothing more than mathematics.

In this tutorial, we will show you some pitfalls when working with money. Meanwhile we will introduce a great package that makes money easy to work with.

Money is not just a number

You can not take 100 Singapore dollar and exchange for 100 US dollar. Money is not just a number. It is consist of a numeric value and a currency.

You should never write your code as below to represent money again:

$price = 100;

Variable $price is meaningless in the context of money.

Let's install the Money package to help us create a meaningful money object:

composer require moneyphp/money

Now we create a price in Singapore dollar:

$price = new Money(100, new Currency('SGD'));

Cent is your friend

When working with money, you should always work the lowest unit, which is in cent. This saves you the hassle of dealing with float dividing issues.

So keep in mind when instantiating a Money object, you are passing in cents.

$price = new Money(100, new Currency('SGD'));

The $price above represents 1 Singapore dollar.

Different currency has different decimal place

Decimal place is not always two for money, so you can not simply use number_format() to format money.

For example, for Japanese Yen, there is no decimal value whereas standard Singapore Dollar has two decimal places. The Money package provides a decimal parser allows us to parse money to a correct decimal format:

$price = new Money(500, new Currency('JPY'));
$currencies = new ISOCurrencies();
$moneyFormatter = new DecimalMoneyFormatter($currencies);
echo $moneyFormatter->format($price);

Learn more about Money

We have just showed you the surface of working with the Money package. It provides a lot of other features such as performing operation, comparison, allocation and so on. Please check out its document at link.

The end

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know