Search code examples
pythonformatfloating-accuracy

printing numbers with consistent or fixed accuracy


These three numbers 1.2, 0.0034, 56000 all have one thing in common: two digits of accuracy. Lets say I want to report computed bandwidth of several very different devices that range from kilobytes per second to gigabytes per second, all of which vary by up to %10. The easiest way for my readers to quickly grasp the results is for me to convert everything to a common unit (say MB/s), line up the decimal points,

    1.2
    0.0034
56000

and avoid printing extraneous digits; if my computed values are 1.193225, 0.00344791, and 56188.5622, then my readers only need to see the above - the rest is noise. Despite extensive formatting options for floating point numbers, Python doesn't seem to have a clean way to print numbers with a fixed-accuracy. What would be the best way to do this?

A note on scoring this question: I'll chose the best (ie. simple, understandable, elegant) answer over the first answer. No need to rush.


Solution

  • import math
    
    
    def round_s(n):
        if not n:
            return n
        e = int(math.floor(math.log10(abs(n)))) - 1
        return round(n, -e)
    
    
    def fmt(n, size):
        return '{n:{size}f}'.format(size=size, n=n).rstrip('0').rstrip('.')
    
    
    numbers = [
        1.193225,
        1.0,
        0,
        -1.0,
        0.00344791,
        -0.00344791,
        56188.5622,
        -56188.5622,
    ]
    
    for n in numbers:
        print '{:12.5f} => {}'.format(n, fmt(round_s(n), 14))
    

    Output:

         1.19322 =>       1.2
         1.00000 =>       1
         0.00000 =>       0
        -1.00000 =>      -1
         0.00345 =>       0.0034
        -0.00345 =>      -0.0034
     56188.56220 =>   56000
    -56188.56220 =>  -56000
    

    Here you go.