java

Money operations are not as easy as you think

Money operations are not as easy as you think

I see this a lot in Stackoverflow and most of the replies always makes me wonder what kind of software is running over there. People ask about operations with currencies (that is, money) and they usually get replies about using doubles and then rounding.

Big no! Floats and doubles don’t represent exact numbers. They represent a number at certain precision. 101 in any coding course. If your application handles prices (and its probable if you are charging for some service), you can’t use float/double. Your language probably have a way to represent exact numbers. In Java we have BigDecimal and… Money!

Money price = Money.of(10.50, "EUR");
MonetaryOperator roundingOperator = MonetaryOperators.rounding(RoundingMode.HALF_UP);
Money newPrice = price.multiply(61).divide(3).with(roundingOperator);

You will be thinking: why so much trouble to do a simple ceil(10.50 * 61 / 3)?

What happens to decimals? What happens to cents? Do you know that there are currencies that don’t have the equivalent to cents (for example, the yen)?

There are a lot of subtleties you just don’t know when handling money (as happens with operations with time!). I don’t know you, but if some people have already taken their time figuring all those things out… I feel safer using their knowledge!

If your language does not have something similar, then… you’ll have to stick to integers and handle with care how many decimals your currencies need. For example, if you want to represent 15.53€, you can handle it as an integer 1553, but you will have to think what happens with rounding in your use cases.

PS: Of course, if you are performing simulations (for example, Montecarlo) or other mathematics stuff, although they represent money, you won’t probably need to apply any of the things I said before. You are already dealing with other precision problems! :)