Python 将变量值打印到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18781344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printing a variable value to 2 decimal places
提问by user2633836
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?
我已经创建了整个程序,这只是其中的一小部分,但我无法将程序打印到小数点后两位。我曾尝试使用先前提出的问题中的“%.2f”,但它不起作用有人可以建议我需要做什么吗?
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.
我想保证存储在变量 total-Exchange 中的值始终为 2 dp。
回答by Dux
If you want the value to be stored with 2 digits precision, use round()
:
如果您希望以 2 位精度存储值,请使用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:
如果您需要更精确地保存变量(例如用于进一步计算),但输出要四舍五入,则建议"%.2f"
对我来说非常适合:
>>>t = 12.987876
>>>print "This converts to %.2f" % t
#This converts to 12.99
回答by KevinB
Tested with Python 3.0
用 Python 3.0 测试
t = 12.987876
print(f'This converts to {t:.2f}')
Result:
结果:
This converts to 12.99
这将转换为 12.99