siesta
siesta

Reputation: 1395

Print a float with precision right justified

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

Upvotes: 26

Views: 31401

Answers (3)

siesta
siesta

Reputation: 1395

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)

Upvotes: 1

Harley
Harley

Reputation: 1524

Python Format Specification Mini-Language

print(f'{symbol:<5}: {name:<44} {buyprices:>10.2f}  change: {val:>5.2f}')

Output:

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

How it works:

<44 (left justified, 44 places)
>5.2f (right justified, 5 places, 2 decimal places) 

Upvotes: 4

Levon
Levon

Reputation: 143047

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).

Upvotes: 34

Related Questions