title: How to create a decimal.Decimal object with a given number of significant figures?
body: <p>The best way I've found to produce a <code>decimal.Decimal</code> number with a specific number of <em><a href="https://en.wikipedia.org/wiki/Significant_figures" rel="nofollow noreferrer">significant figures</a></em> is the one used to initialize the variable <code>kluge</code> below:</p>
  
  <pre><code>import decimal
  THIS_IS_JUST_AN_EXAMPLE = 0.00001/3.0
  with decimal.localcontext() as c:
     c.prec = 5
     kluge = decimal.Decimal(THIS_IS_JUST_AN_EXAMPLE) + decimal.Decimal(0)
     naive = decimal.Decimal(THIS_IS_JUST_AN_EXAMPLE)
     print repr(kluge)
     print repr(naive)
  
  # Decimal('0.0000033333')
  # Decimal('0.00000333333333333333374718233758915442166426146286539733409881591796875')
  </code></pre>
  
  <p>The first line of output shows the desired <code>decimal.Decimal</code> number, with 5 significant figures.  The second line in the output shows what happens if one does not add the</p>
  
  <pre><code>+ decimal.Decimal(0)
  </code></pre>
  
  <p>to the RHS of the initialization; without it, the result has unwanted and unhelpful excess precision.</p>
  
  <p>Even without the <code>+ decimal.Decimal(0)</code> hack, the code strikes me as more verbose than it needs to be.</p>
  
  <p>What's the correct approach to creating a <code>Decimal</code> with a desired number of significant figures?</p>
  
  <hr>
  
  <p>This question is not a duplicate of <a href="https://stackoverflow.com/q/15076310/559827">Format Python Decimal object to a specified precision</a>.  Look at the output below.</p>
  
  <pre><code>import math
  import decimal
  base = math.pi
  with decimal.localcontext() as c:
      c.prec = 13
      for exponent in [6, 4, 2, 0, -2, -4, -6]:
          scale = 10**exponent
          kluge = decimal.Decimal(base * scale) + decimal.Decimal(0)
          print repr(kluge)
  
  # Decimal('3141592.653590')
  # Decimal('31415.92653590')
  # Decimal('314.1592653590')
  # Decimal('3.141592653590')
  # Decimal('0.03141592653590')
  # Decimal('0.0003141592653590')
  # Decimal('0.000003141592653590')
  </code></pre>
  
  <p>The items shown in the output above cannot be obtained using the method given in the answer to <a href="https://stackoverflow.com/q/15076310/559827">Format Python Decimal object to a specified precision</a>, simply because <strong>this question has nothing to do with formatting output.</strong></p>
  
  <p>This question is about how to use a <em>specific module</em> (<code>decimal</code>) to create certain objects of a class defined by that module.  More specifically, it is about looking for a way to use the <code>decimal</code> module to achieve the result shown without having to resort to adding <code>decimal.Decimal(0)</code>.</p>