[英]Formatting to two decimal places in python
Fairly new to coding and having some confusion with my homework. 编码非常陌生,对我的作业有些困惑。 I want to have the printed results only go to two decimal places and not any farther.
我希望打印的结果只保留两位小数,而不是更远的位数。 I have been messing around with some format options and trying to find the answer online but couldn't understand what I needed to do, any help is much appreciated, thanks!
我一直在弄乱一些格式选项,试图在网上找到答案,但是不明白我需要做什么,非常感谢您的帮助!谢谢!
#Ingredients per 48 cookies
sugar = 1.5
butter = 1
flour = 2.75
#what percent of 48 are the ingredients
sugar1 = (1.5/48)
butter1 = (1/48)
flour1 = (2.75/48)
#ask for amount of cookies from user
cookies = int (input('How many cookies would you like to bake? '))
#calculate ingredient amounts
sugar2 = (sugar1 * cookies)
format(sugar2, '.2f')
butter2 = (butter1 * cookies)
format(butter2, '.2f')
flour2 = (flour1 * cookies)
format(flour2, '.2f')
print ('To make', cookies, ' you need', sugar2, 'cups of sugar,',
butter2, 'cups of butter, and', flour2, ' cups of flour.')
If you want to output 2 digits: 如果要输出2位数字:
for n in [1.23,1.234,1.1,1.7846]:
print('{:.2f}'.format(n))
Output: 输出:
1.23
1.23
1.10
1.78
Have a quick read here for python 3 formattings: https://pyformat.info/#number or here: https://docs.python.org/3.1/library/string.html#format-examples 在此处快速阅读python 3格式: https : //pyformat.info/#number或此处: https : //docs.python.org/3.1/library/string.html#format-examples
format
不是声明,也不是改变其参数的声明:它会产生一个字符串,您需要在输出中包含该字符串。
例如:
print('%.2f' % sugar2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.