Working with the League
This article is part of series in Working with the League :
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.
Table Of Content
- Money is not just a number
- Cent is your friend
- Different currency has different decimal place
- Learn more about Money
- The end
1. 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:
Variable $price is meaningless in the context of money.
Let's install the Money package to help us create a meaningful money object:
Now we create a price in Singapore dollar:
2. 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.
The $price above represents 1 Singapore dollar.
3. 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:
4. 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.
5. 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.