Correct usage of Decimal objects in this expression
<p>I need to calculate the area of any regular polygon. I acquired this formula from a good ol' google:</p>

<pre><code>(n * l**2) / (4 * math.tan((180/n) * (math.pi/180)))
</code></pre>

<p>No matter how I use <code>decimal.Decimal</code> with these values I can never get it to work as intended. <code>n</code> and <code>l</code> are given as floats.</p>

<p>Can someone apply decimal object to this please? When <code>n</code> is 4 and <code>l</code> is 2, it should return <code>4</code>, but currently it returns <code>4.00000000000000156234</code> (or something along those lines).</p>

<p>You need to set the precision for the decimal object. Pi is an infinite decimal number, so the precision won't be a whole number.</p>

<p>You can do</p>

<pre><code>from decimal import *

getcontext().prec = 1
</code></pre>

<p>or add to the decimal object by rounding down.</p>

<pre><code>&gt;&gt;&gt; Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
</code></pre>

<p><a href="https://docs.python.org/3.5/library/decimal.html" rel="nofollow">take from docs</a></p>

python python-3.x decimal