Python, print all floats to 2 decimal places in output

前端 未结 7 1111
野性不改
野性不改 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:46

    If you are looking for readability, I believe that this is that code:

    print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
        'kg': var1,
        'lb': var2,
        'gal': var3,
        'l': var4,
    }
    
    0 讨论(0)
  • 2020-12-07 18:47

    I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-07 18:51

    Well I would atleast clean it up as follows:

    print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)
    
    0 讨论(0)
  • 2020-12-07 19:03

    If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:

    def fp(*args):  # fp means 'floating print'
        tmps = []
        for arg in args:
            if type(arg) is float: arg = round(arg, 2)  # transform only floats
            tmps.append(str(arg))
        print(" ".join(tmps)
    

    Use fp() in place of print ...

    fp("PI is", 3.14159) ... instead of ... print "PI is", 3.14159

    0 讨论(0)
  • 2020-12-07 19:06

    Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

    print         '%.2f' % var1, \
          'kg =' ,'%.2f' % var2, \
          'lb =' ,'%.2f' % var3, \
          'gal =','%.2f' % var4, \
          'l'
    
    0 讨论(0)
提交回复
热议问题