Skip to main content
andrés ignacio torres

Handling monetary values in code

Photo of a screen showing a close-up of programming code

Photograph by Rashed Paykary on Unsplash.

Every developer will eventually have to deal with monetary values in their code some time. This is a tricky thing to get right, and it is absolutely necessary to do so.

My two cents (no pun intended) on the matter are:

Don't reinvent the wheel #

There are many libraries (e.g. dinero for Python) out there that have been built to handle monetary values and their edge cases. They're usually tried and tested and will consider a lot of scenarios that you might not have thought of. Highly recommended!

Use the right data type #

For storage and transport, the right data type is key. Avoid floating point numbers, as they can introduce rounding errors when adding, substracting or otherwise making calculations with money.

Consider using fixed-point numbers (e.g. Decimal in Python), or integers (e.g. treat money as cents instead of dollars, like Stripe does). This will help avoid rounding errors by design.

Always consider localization #

Different countries and regions have different ways of formatting monetary values. For example, three dollars and fifty cents would be written as $3.50 in Canada but $3,50 in France (note the comma instead of the full stop).

This is particularly important if you are working on code that sends or receives monetary values to another system, or that parses monetary values from user input (e.g. from string). Make sure there is a clear contract between the two systems or the user input and the code for the format of the monetary values. Consider how your code will behave if deployed in a different region or country, and if the system locale can change at runtime.

Log everything! #

Or, at least, log the most important things to the extend you're allowed to. That way you can reconstruct any operation when needed and find out what, if anything, went wrong (and things will go wrong).

Test, test, test! #

Finally, test everything thoroughly. Add unit tests for all the testable code, add integration tests for the components that interact with each other, and perform end-to-end tests every so often.