Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
duanev Avatar asked May 16 '26 23:05

duanev


1 Answers

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.

like image 80
GaretJax Avatar answered May 18 '26 11:05

GaretJax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!