Set global output precision python

前端 未结 4 2048
清酒与你
清酒与你 2021-01-04 19:56

I\'ve written a library of functions to make my engineering homework easier, and use them in the python interpreter (kinda like a calculator). Some return matrices, some ret

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 21:01

    One idea would be to add from __future__ import print_function (at the very top) and then override the standard print function. Here's a very simple implementation that prints floats with exactly two digits after the decimal point:

    def print(*args):
        __builtins__.print(*("%.2f" % a if isinstance(a, float) else a
                             for a in args))
    

    You would need to update your output code to use the print function, but at least it will be generic, rather than requiring custom formatting rules in each place. If you want to change how the formatting works, you just need to change the custom print function.

提交回复
热议问题