title: How to truncate double to N decimal places?
body: <p>I want to round my double value down to N decimal places (say, one), esentially just leaving out all the digits that follow:</p>
  
  <pre><code>0.123 #=&gt; 0.1
  0.19  #=&gt; 0.1
  0.2   #=&gt; 0.2
  </code></pre>
  
  <p>This question has been brought up numerous times, for example <a href="https://stackoverflow.com/a/2808648/1815052">here</a> and <a href="https://stackoverflow.com/a/5710926/1815052">here</a>. The recommended approach is to use <code>BigDecimal</code> and then scale it, in particular to avoid expensive converting to string and back. The rounding mode I need is apparently <code>RoundingMode.DOWN</code>.</p>
  
  <p>So the method is something like this:</p>
  
  <pre><code>static double truncate(double value, int places) {
      return new BigDecimal(value)
          .setScale(places, RoundingMode.DOWN)
          .doubleValue();
  }
  </code></pre>
  
  <p>But, due to the loss of precision, it returns somewhat unexpected results:</p>
  
  <pre><code>truncate(0.2, 1) #=&gt; 0.2
  truncate(0.3, 1) #=&gt; 0.2
  truncate(0.4, 1) #=&gt; 0.4
  
  truncate(0.2, 3) #=&gt; 0.2
  truncate(0.3, 3) #=&gt; 0.299
  truncate(0.4, 3) #=&gt; 0.4
  </code></pre>
  
  <p>This begs for two questions:</p>
  
  <ol>
  <li><p>Is it how it's supposed to work for <code>0.3</code>? Why would there be a loss of precision in this case? Doesn't it defeat the whole purpose of having <code>BigDecimal</code>?</p></li>
  <li><p>How do I correctly truncate my values?</p></li>
  </ol>
  
  <p>Thanks.</p>