Specifying number of decimal places in Python

Viewed 143303

When accepting user input with a decimal in Python I'm using:

#will input meal subtotal  
def input_meal():  
    mealPrice = input('Enter the meal subtotal: $')  
    mealPrice = float (mealPrice)  
    return mealPrice  

which returns exactly what is entered - say $43.45
but when using that value to calculate and display tax I'm using:

#will calculate 6% tax  
def calc_tax(mealPrice):  
    tax = mealPrice*.06  
    return tax

which returns a display of $ 2.607 using

mealPrice = input_meal()
tax = calc_tax(mealPrice)
display_data(mealPrice, tax)  

How can I set that to $2.61 instead?
Forgive me, I realize this is basic stuff but they don't call it Intro for nothing...

Thanks!

6 Answers

This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.

I recommend you use the standard library locale.currency object. It seems to have been created to address this problem of currency representation.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.

Use round() function.

round(2.607) = 3
round(2.607,2) = 2.61
Related