How do you preserve precision when scaling a Decimal?
<p>How can you scale a <a href="https://docs.python.org/library/decimal.html#decimal.Decimal" rel="nofollow"><code>Decimal</code></a>, but keep its original precision? E.g.,</p>

<pre><code>&gt;&gt;&gt; from decimal import Decimal
&gt;&gt;&gt; Decimal('0.1230')
Decimal('0.1230') # Precision is 4.
</code></pre>

<p>Multiplication does not preserve the original precision:</p>

<pre><code>&gt;&gt;&gt; Decimal('0.1230') * 100
Decimal('12.3000') #  Precision is 6.
&gt;&gt;&gt; Decimal('0.1230') * Decimal('100')
Decimal('12.3000') # Precision is 6.
</code></pre>

<p>The <a href="https://docs.python.org/library/decimal.html#decimal.Decimal.shift" rel="nofollow"><code>.shift()</code></a> method only keeps the same number of decimal places when shifting by a negative amount:</p>

<pre><code>&gt;&gt;&gt; Decimal('0.1230').shift(2)
Decimal('12.3000') # Precision is 6.
&gt;&gt;&gt; Decimal('0.1230').shift(-2)
Decimal('0.0012') # Precision is 2.
</code></pre>

<p>The <a href="https://docs.python.org/library/decimal.html#decimal.Decimal.scaleb" rel="nofollow"><code>.scaleb()</code></a> method will scale a decimal number while preserving its precision. From the documentation:</p>

<blockquote>
  <p>scaleb(other[, context])</p>
  
  <blockquote>
    <p>Return the first operand with <em>exponent</em> adjusted by the second.</p>
  </blockquote>
</blockquote>

<p>The key part is that the <em>exponent</em> gets adjusted and thus maintains precision.</p>

<pre><code>&gt;&gt;&gt; Decimal('0.1230').scaleb(2)
Decimal('12.30') # Precision is 4.
&gt;&gt;&gt; Decimal('0.1230').scaleb(-2)
Decimal('0.001230') # Precision is 4.
</code></pre>

python python-2.7