title: Unpredictability of the BigDecimal(double) constructor
body: <p>I started using Sonar recently in a project, and i got a PMD rule broken about using the constructor <code>new BigDecimal(double val)</code>. When i read the java documentation, i found that new BigDecimal(double val) is somewhat unpredictable and that I should use <code>new BigDecimal(String val)</code> which is predictable.</p>
  
  <p>Here is what javadoc says for <code>BigDecimal</code> <code>public BigDecimal(double val)</code>:</p>
  
  <blockquote>
    <p>Translates a double into a BigDecimal which is the exact decimal
    representation of the double's binary floating-point value. The scale
    of the returned BigDecimal is the smallest value such that (10scale ×
    val) is an integer.</p>
    
    <p>Notes:</p>
    
    <p>The results of this constructor can be somewhat unpredictable. One
    might assume that writing <code>new BigDecimal(0.1)</code> in Java creates a
    <code>BigDecimal</code> which is exactly equal to 0.1 (an unscaled value of 1,
    with a scale of 1), but it is actually equal to
    0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that
    matter, as a binary fraction of any finite length). Thus, the value
    that is being passed in to the constructor is not exactly equal to
    0.1, appearances notwithstanding.</p>
    
    <p>The String constructor, on the other hand, is perfectly predictable:
    writing <code>new BigDecimal("0.1")</code> creates a <code>BigDecimal</code> which is
    exactly equal to 0.1, as one would expect. Therefore, it is generally
    recommended that the String constructor be used in preference to this
    one.</p>
    
    <p>When a double must be used as a source for a <code>BigDecimal</code>, note that
    this constructor provides an exact conversion; it does not give the
    same result as converting the double to a String using the
    <code>Double.toString(double)</code> method and then using the
    <code>BigDecimal(String)</code> constructor. To get that result, use the static
    <code>valueOf(double)</code> method.</p>
  </blockquote>
  
  <p>Why does this constructor really exists? Isnt <code>new BigDecimal(String val)</code> enough for that matter? When should I use the <code>new BigDecimal(double val)</code> constructor?</p>