This is a pretty easy topic but most of us don't know which is the best type to use to store money.
Eg: for $5.9, most people would go with a
float . They think it is correct, but it is not.
Let's quickly talk about it.
Before jumping into the topic, I've been working with
Money for several years now (for critical apps). So I will share an overview with you guys.
You will learn more when googling about the "Floating point problem". Here is a quick summary:
Float stores an approximate value
5.9 above, you might think it is stored under the memory/storage as
5.9. No it's not.
It actually stored as
For critical apps that involved money calculation (eg fintech, quotation, invoicing,...), when you do the math, it basically goes wrong.
The same goes for the DB engines, not only coding language.
We have 2 solutions
Decimal will store the exact value (
5.9 will always be
6.99 will always be
Most of the popular DB engines are supporting the
The decimal type uses 5-17 bytes, so don't worry about the big money numbers.
For coding language, most languages don't have the built-in
decimal type (too bad), which I really like C# about this one, they have it.
Using decimal, you can do the math and all the stuff normally like when you're using
Another alternative for money type. You probably would ask how are we gonna handle the decimal places.
Yeah, when using an integer, we will store the money as "cents", not dollars.
599 as integer. $
600 as integer
Pretty simple, isn't it?
integer never lie.
Things you need to take care of when using integer:
Converting dollars to cents everywhere (simply
dollar * 100)
- You probably need a global abstraction for this
Some currencies (eg Vietnamese Dong or Indonesian Rupiah) don't have decimal places, you can do the
*100for it, if you like.
Well, that's pretty much it. When it comes to
Money, let's deal it with caution, nobody want to lose any money 😉