Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

3
  • 11
    There's no way you can altogether "avoid" floating point arithmetic errors. The number of bits used in representing a number will always be finite. All you can do is to use data types with higher precision (bits). Commented Oct 7, 2008 at 17:17
  • 1
    That is true. I will edit my answer to more accurately reflect the use of BigDecimal. Commented Oct 7, 2008 at 17:29
  • 6
    I'll add a note that BigDecimal division needs to be treated a little bit differently than +,-,* since by default it will throw an exception if it cannot return an exact value (1 / 3, e.g.). In a similar situation I used: BigDecimal.valueOf(a).divide(BigDecimal.valueOf(b), 25, RoundingMode.HALF_UP).doubleValue(), where 25 if the maximal digits of precision (more than needed by the double result). Commented Jul 12, 2011 at 16:05