Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the <a href="http://docs.python.org/2/library/decimal.html#decimal.Decimal.normalize" rel="noreferrer"><code>normalize</code></a> method to remove extra precision.</p> <pre><code>&gt;&gt;&gt; print decimal.Decimal('5.500') 5.500 &gt;&gt;&gt; print decimal.Decimal('5.500').normalize() 5.5 </code></pre> <p>To avoid stripping zeros to the left of the decimal point, you could do this:</p> <pre><code>def normalize_fraction(d): normalized = d.normalize() sign, digits, exponent = normalized.as_tuple() if exponent &gt; 0: return decimal.Decimal((sign, digits + (0,) * exponent, 0)) else: return normalized </code></pre> <p>Or more compactly, using <code>quantize</code> as suggested by <a href="https://stackoverflow.com/questions/11227620/drop-trailing-zeros-from-decimal/11227743#comment14749895_11227743">user7116</a>: </p> <pre><code>def normalize_fraction(d): normalized = d.normalize() sign, digit, exponent = normalized.as_tuple() return normalized if exponent &lt;= 0 else normalized.quantize(1) </code></pre> <p>You could also use <code>to_integral()</code> as shown <a href="https://stackoverflow.com/a/18769210/577088">here</a> but I think using <code>as_tuple</code> this way is more self-documenting. </p> <p>I tested these both against a few cases; please leave a comment if you find something that doesn't work. </p> <pre><code>&gt;&gt;&gt; normalize_fraction(decimal.Decimal('55.5')) Decimal('55.5') &gt;&gt;&gt; normalize_fraction(decimal.Decimal('55.500')) Decimal('55.5') &gt;&gt;&gt; normalize_fraction(decimal.Decimal('55500')) Decimal('55500') &gt;&gt;&gt; normalize_fraction(decimal.Decimal('555E2')) Decimal('55500') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload