There is no simple method of avoiding rounding errors in general-purpose floating-point arithmetic. The number 0.3
does not have an exact binary floating-point representation.
I would suggest reading What Every Computer Scientist Should Know About Floating-Point Arithmetic to familiarize yourself with the trade-offs inherent to floating-point representation of numbers.
To actually solve your issue, you should ask yourself a few questions:
- How strict is your requirement for precision? Why is
0.30000000000000004
outside your margin for error? Is it acceptable to round your results?
- Is there any way you could represent your numbers and perform most of your arithmetic with integers? E.g. if you know that you'll only encounter rational numbers, they can be represented using an integer quotient and an integer denominator. From there, you can attempt to defer casting to float for as long as possible to prevent cumulative rounding errors.
- If you cannot perform your calculations on integers, is there an alternate datatype you can use, such as
BigDecimal
?
Ultimately, when it comes to issues with floating-point precision, you'll often have to tailor the solution to the requirements posed by your specific issue.