Shawn Driscoll's Tech Blog


Stuff That Happened in the Past

Wednesday, May 16, 2012

Printing Formatted Floats in Python

A long time ago, I had written a program to do a die roll chart for GURPS. I used QBASIC to get the results.

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.

2 comments:

  1. HTML formatting is going to mess around with the number of spaces in the output string, but you should be able to cut-n-paste the Python lines into a shell and see the results. I think this is what you're looking for but correct me if I'm wrong. You can do something similar in C.

    >>> import math
    >>> math.pi
    3.141592653589793
    >>> '%10.2f' % math.pi
    ' 3.14'
    >>> '%8.4f' % math.pi
    ' 3.1416'
    >>> '%12.1f' % math.pi
    ' 3.1'

    ReplyDelete
    Replies
    1. I'm starting to see. The first number is the total number of digits (not just the number of digits on the left of the decimal). Maybe that was my mistake? I'll try again.

      Delete