I am working with a Python script that prints many floating point numbers. Within each print
command, I use round(x, 3)
to round the printed number x
to 3 decimal places before printing. Here is a simplified example:
x1 = 1.61803398875
print('x1 = ' + str(round(x1, 3))) # x1 = 1.618
x2 = x1**2
print('x2 = ' + str(round(x2, 3))) # x2 = 2.618
x3 = 1/(x2-1)
print('x3 = ' + str(round(x3, 3))) # x3 = 0.618
The actual code contains hundreds of these print commands. Is there a more efficient way to perform the rounding part of this script? For example, is there a single overarching command that will round all printed floats to a given precision, as there is for numpy
and pandas
variables?
I am looking for a solution that does not involve moving or combining the print
commands or converting the printed variables to numpy
and pandas
variables before printing.
Using f-strings is a much easier way to specify rounding in string representations of numbers:
x1 = 1.61803398875
print(f'x1 = {x1:.3f}') # x1 = 1.618
x2 = x1**2
print(f'x2 = {x2:.3f}') # x2 = 2.618
x3 = 1/(x2-1)
print(f'x3 = {x3:.3f}') # x3 = 0.618
but you do still need to repeat the .3f
part each time.
If you wanted to DRY as much as possible, you could write a wrapper:
def print_var(var: str, val: float) -> None:
print(f'{var} = {val:.3f}')
x1 = 1.61803398875
print_var('x1', x1) # x1 = 1.618
x2 = x1**2
print_var('x2', x2) # x2 = 2.618
x3 = 1/(x2-1)
print_var('x3', x3) # x3 = 0.618
or you could redefine print
(I wouldn't recommend this one, personally):
import builtins
def print(*args, **kwargs):
rounded_args = [
f'{arg:.3f}' if isinstance(arg, float) else arg
for arg in args
]
builtins.print(*rounded_args, **kwargs)
x1 = 1.61803398875
print('x1 = ', x1) # x1 = 1.618
x2 = x1**2
print('x2 = ', x2) # x2 = 2.618
x3 = 1/(x2-1)
print('x3 = ', x3) # x3 = 0.618