简体   繁体   中英

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:

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

format不是声明,也不是改变其参数的声明:它会产生一个字符串,您需要在输出中包含该字符串。

例如:

print('%.2f' % sugar2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM