Print a float with precision right justified

24,511

Solution 1

This shows an example of how to format your output with two decimal points using the older % formatting method:

v1 = 55.39
v2 = -1.15
v3 = 6.54
v4 = 0.00

print '%8.2f   %8.2f' % (v1, v2)
print '%8.2f   %8.2f' % (v3, v4)

the corresponding output:

   55.39      -1.15
    6.54       0.00

Alternatively, you can use the "new and improved" .format() function which will be around for a while and is worth getting to know. The following will generate the same output as above:

print '{:8.2f}  {:8.2f}'.format(v1, v2)
print '{:8.2f}  {:8.2f}'.format(v3, v4)

Both sets of formatting directives allocate 8 spaces for your number, format it as a float with 2 digits after the decimal point. You'd have to adjust these values to fit your needs.

Using this approach to format your output will be easier I think since .format() will give you a lot of control over the output (incl. justifying, filling, precision).

Solution 2

Never mind, I figured this out right after posting my question of course...

changed to this:
    def change_value(self, sym, buy, sell):
        self.sym = sym
        temp = float(buy) - float(sell)
        self.val = "%.2f" % temp




and then called str(Instance1.val).rjust(10)
Share:
24,511
siesta
Author by

siesta

Updated on February 04, 2022

Comments

  • siesta
    siesta about 2 years

    I'm somewhat of a newb to programming with python so please go easy on me. I'm trying to call the string attribute rjust and also specify precision for a floating point. Here's the code and sample output (note the 0.00 is not justified to the right):

    print '%s: %s %s \tchange: %.2f' % (Instance1.symbol.ljust(5), 
        Instance1.name.ljust(50), Instance1.buyprices.rjust(10), Instance1.val)
    

    OUTPUT:

    AXP  : American Express Company                          55.38  change: -1.15  
    AXR  : Amrep Corp.                                       6.540  change: 0.00