What is the best practice for dealing with those cases?
When it comes to currency, the best thing is usually* to not use floats. Use integers for those. Here are some of the problems with floats when it comes to currency:
Most decimal fractions cannot be represented exactly
When the numbers get too big, floats silently lose precision in the last integer digits
But simply using an integer is not enough. If you just store the amount of cents, you will likely have problems when doing calculations with interests and such. Instead, you want to store for instance thousands of a cent. A millicent if you will. But do note that this does not automatically solve all problems with it.
Also bear in mind that storing millicents will require very big integers. a 32 bit number can store 4 billion millicents, which would be just 40,000 dollars. So a 64 bit integer is preferred.
Here is a post that describes problems with using floats for currency very well: https://software.codidact.com/posts/284175
A quote from celtschk's answer in the above link:
For example, say that you've got 128 dollars invested with an interest of 0.6%, but in the first year you only get half of that percentage. So how much do you get in the first year? Well, obviously 0.3% of 128 dollars are 38.4 cents, which then get rounded to 38 cents. But let's do the calculation differently: First, we calculate the interest you'd normally get: 0.6% of 128 dollars are 76.8 cents, which get rounded to 77 cents. And then half of this is 38.5 cents which get rounded to 39 cents. This is one cent more.
To avoid this type of error, intermediate calculations should always be done with a higher precision, and only the end result be converted to integer cents with proper rounding.
* No rule is without exceptions though. Quoted from this answer:
To give an example, I once was engaged in a lengthy discussion with a programmer who was insisting on representing cashflows with decimals instead of floating point numbers in a software computing risks. In bookkeeping applications decimals are of course the only sane choice (or integers), but for risk management using a lot of stochastic models and numerical approximations, floating point numbers are the right choice.
As Eric Postpischil mentioned in comments below:
The “fix” is to understanding mathematics and the representations types use and to design software for the particular situations.
If we're not talking about currency, but the general "convert float to int" case, then there isn't really any best practice. It all comes down to the individual situation. Using round
will typically give "more correct" results.