How can I improve formatting of floats output from my tax calculator?
<p>I didn't have any problems writing this much, but the output numbers are a little wonky. Sometimes I'll get something like 83.78812, for example, and I'd rather round it up to 83.79.</p>

<p>Here's the code itself:</p>

<pre><code>#This is a simple tax calculator based on Missouri's tax rate.

while True:
tax = 0.076
cost = float(raw_input("How much does the item cost? $"))
taxAmount = tax * cost
final = taxAmount + cost
if cost &gt; 0:
    print "Taxes are $" + str(taxAmount) + "."
    print "The total cost is $" + str(final) + "."
else:
    print 'Not a valid number. Please try again.'
</code></pre>

<p>I've seen people mention that I should be using ints instead of floats, but my tax-rate is over three characters past the decimal. Furthermore, typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning. I don't know how to fix either of these things.</p>

<blockquote>
  <p>"typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning."  </p>
</blockquote>

<p>To do this, you can use a while loop with <code>try &amp; catch</code> That will keep on prompting for the item cost until it gets appropriate value</p>

<p>Use <code>round()</code> method to round up your value. It takes two parameters, first one is the value and second one is the position where to round up. </p>

<p>Format your result with python string formatting using the placeholder <code>%.2f</code> (2 digits after decimal point)</p>

<pre><code>tax = 0.076
cost = 0
parsed = False
while not parsed:
    try:
        cost = float(raw_input("How much does the item cost? $"))    
        parsed = True
    except ValueError:
        print 'Invalid value!'
taxAmount = tax * cost
final = taxAmount + cost
if cost &gt; 0:
    print "Taxes are $%.2f." % round(taxAmount, 2)
    print "The total cost is $%.2f." % round(final, 2)
else:
    print 'Not a valid number. Please try again.'
</code></pre>

python python-2.7 calculator number-formatting