Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a float with precision right justified

Tags:

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 
like image 257
siesta Avatar asked Jul 15 '12 04:07

siesta


People also ask

How do you print a precision float in Python?

There are many ways to set the precision of the floating-point values. Some of them are discussed below. Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.

How do you justify right in Python?

Note: If you want to right justify the string, use ljust(). You can also use format() for formatting of the strings.

How do you print float to two decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


2 Answers

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

like image 59
Levon Avatar answered Sep 17 '22 15:09

Levon


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) 
like image 26
siesta Avatar answered Sep 20 '22 15:09

siesta