With the float
there’s nothing to do. I’ve essentially answered in that reply (has several links to other information, I recommend reading all, especially those that are in English, if you can). This seems to be one of the most common problems encountered in novice (and even experienced programmers).
float
cannot be used to work with money, it lacks precision and is not because it lacks decimal places, could have 30 million decimal places and would still have problems. The difficulty is how it is calculated and represented. It’s very fast for being binary but it can’t represent all the possible numbers, so the number you want to store possibly will be represented by another number very close to what you want. This is not a problem in most scientific calculations but is impractical for money.
The float
can be shown with two decimal places but it always has several houses in its representation. And again, this is not what causes the problem.
And there’s no point in using double
. Not even a superdouble, or halffloat if they existed. It will probably only create more problem.
The correct is the use of Decimal which is the simplest solution and is usually very efficient. Or some library to deal specifically with Money or the Official API for money which is a bit inferior (it seems that comes a new API in Java 9, do not know if it solves the problem). Beware, these libraries can be exaggerated for what you need. These guys work with decimal accuracy, that is, they can represent any number without error.
Ex.: BigDecimal bd = new BigDecimal("123.45");
Care must be taken anyway, these classes do not solve all problems alone.
To string is used to avoid rounding problems since Java does not have a literal for decimal types.
Related: Best kind of data to work with money? (in C#)
– Math