Python, print all floats to 2 decimal places in output

前端 未结 7 1142
野性不改
野性不改 2020-12-07 18:38

I need to output 4 different floats to two decimal places.

This is what I have:

print \'%.2f\' % var1,\'kg =\',\'%.2f\' % var2,\'lb =\',\'%.2f\' % va         


        
7条回答
  •  借酒劲吻你
    2020-12-07 18:49

    Format String Syntax.

    https://docs.python.org/3/library/string.html#formatstrings

    from math import pi
    var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
    '{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)
    

    The output would be:

    '3.14, kg=6.28, lb=9.42, gal=12.57'
    

提交回复
热议问题