Wednesday, May 16, 2012
Printing Formatted Floats in Python
Since learning Python, I thought I'd give it a shot at calculating the results for me. But getting the decimal point to line up nice in the percent column was not automatic for me. I could not find a print "formatter" for Python 2.5.4 that would let me state how many digits I wanted displayed on each side of the decimal point. I looked on the Interweb and saw lots of people asking the same question about Python and not getting much help. I figured Python 3's new print() function may very well have such a feature, but I got my system all perfect with verison 2.5.4 for now.
So I thought back to 1979 when I had a class assignment to print a table of decimal values which needed its columns all lined up. This was on an HP-2000F running BASIC. The trick was, we couldn't use "PRINT USING" to print the floating-point numbers.
This line from Python is not as robust as that. For I only needed one digit after the decimal point here. And I'm still using a print "formatter". Here is the line:
print '%2d.%d' % ((dr[i] * 100 / n), ((dr[i] * 100. / n) - (dr[i] * 100 / n)) * 10)
The first value is the "10"s or "1"s digit with nothing after the decimal. The second value is a float of the first value minus the first value, leaving just the digits after the decimal point which gets multiplied by ten and rounded down. NOTE: There is a "." printed between both values.
Anyway... I'm posting this so that aliens exploring our burnt out world may find this bit of info useful.