Seth Phat
Seth Phat Blog

Follow

Seth Phat Blog

Follow
Type for Money

Type for Money

Seth Phat's photo
Seth Phat
ยทDec 4, 2022ยท

2 min read

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 double or 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.

Problem

You will learn more when googling about the "Floating point problem". Here is a quick summary:

Float stores an approximate value

So for 5.9 above, you might think it is stored under the memory/storage as 5.9. No it's not.

It actually stored as 5.899999999...

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.

Solutions

We have 2 solutions

Use Decimal

Decimal will store the exact value (5.9 will always be 5.9, 6.99 will always be 6.99)

Most of the popular DB engines are supporting the decimal type.

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 float or double.

Use Integer

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.

Eg: $5.99 => 599 as integer. $6 => 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 *100 for it, if you like.

Conclusion

Well, that's pretty much it. When it comes to Money, let's deal it with caution, nobody want to lose any money ๐Ÿ˜‰

Cheers!

ย 
Share this