Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing a variable value to 2 decimal places [duplicate]

I am trying to create a currency converter that prints a final value out to 2 decimal places.

I have created the entire program and this is just a small portion of it but I can't get the program to print to 2 decimal places. I have tried using "%.2f" from previously asked questions but it doesn't work can anybody suggest what I need to do?

The program I have so far is

conversion_Menu= "What do you want to convert?\n1.Pound Sterling\n2.Euro\n3.USD\n4.Japanese Yen"
x = input (conversion_Menu)
if x == "1":
    sterling_Menu = "What do you want to convert to?\n1.Euro's\n2.USD\n3.Japanese Yen"
    y = input (sterling_Menu)
    currency_Total = float(input("How much do you wish to exchange?"))
    total_Exchange = currency_Total * sterling_Conversion
    print ("This converts to", total_Exchange) 

I want to guarantee that the value stored in variable total-Exchange is always to 2 dp.

like image 530
user2633836 Avatar asked Sep 13 '13 08:09

user2633836


1 Answers

If you want the value to be stored with 2 digits precision, use round():

>>>t = 12.987876
>>>round(t,2)
#12.99

If you need the variable to be saved with more precision (e.g. for further calculations), but the output to be rounded, the suggested "%.2f" works perfectly for me:

>>>t = 12.987876
>>>print "This converts to %.2f" % t
#This converts to 12.99
like image 115
Dux Avatar answered Sep 30 '22 19:09

Dux