This is due to how floating point numbers are stored. When writing
a code, sometimes it behaves in an intended way, sometimes it doesn't
(like the one above). Is there a way to "predict" when the code is ok and
when isn't ? Are there any tips to be aware of to get around that kind
of problems ?
The name of the mathematical field you're asking about is "Numerical Analysis". What you're asking for doesn't fit into this little box here. And "get around" is the wrong attitude. It's a feature, not a bug.
No. Using BigDecimal just because you don't understand how floating-point numbers work would be... um... short-sighted. And it wouldn't help, either. As soon as you divide 1 by 3 then you have to know how decimal numbers work, which is essentially the same problem.
Edit: I forgot the forum hasn't been automated to provide the mandatory link for people who ask this question. We still have to do it by hand.