Luke Curtis

Luke Curtis

Software Developer and Project Manager

Contact Me

Always in Ints - Money in Software

11/04/2019 (1 week ago) | Luke Curtis

Storing monetary values and what type to store them as is always up for debate, and there is not true answer to this question. But I thought I'd delve into what we're currently doing as at least for us, it works flawlessly.

To do this we're going to store a price on a product and then create an attribute which is dollar_price and go from there, like so:

Divide it by 100, right?

Divide it by 100, right?

We're not done yet however. Dividing by 100 isn't always the best way to do this, I mean sure it works fine but its pretty inflexible, what if you needed to add in comma's or make sure it always had two leading zeros?

Well you'd then do something like this:

You can now go ahead and use PHP money format however you like

You can now go ahead and use PHP money format however you like

9 times out of 10 this is fine. A lot of people stop here and call it a day. But there's one more change we can make to make it a lot more flexible.

To do that we'll leverage PHP Money which is a great package for managing . money. It looks something like this:

Our accessor

Our accessor

Now I know this looks a bit more verbose, but think about how much more control this gives you? Need to convert to currencies based on user location? Easy. Need to convert the price on demand? Done. It even can give you a spot exchange rate out of the box so no need to worry about giving incorrect conversions either.