9

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.

user2633836
  • 131
  • 3
  • 5
  • 13

2 Answers2

7

Tested with Python 3.0

t = 12.987876
print(f'This converts to {t:.2f}')

Result:

This converts to 12.99

giusti
  • 3,156
  • 3
  • 29
  • 44
KevinB
  • 101
  • 1
  • 4
  • 2
    This answer is correct. Please do not flag answers you don't like (even if you think they are incorrect). Leave comments to help authors improve their answers. Only flag answers that break the site rules. – giusti Aug 26 '18 at 19:39
  • I agree with this, that said the question is a duplicate and should probably be closed (and it's also very old). A flag is not justified – Jean-François Fabre Aug 26 '18 at 19:46
  • This is now the "best" way of doing it – George Ogden Oct 26 '21 at 09:33
6

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
Dux
  • 1,226
  • 10
  • 29