Basically, I'm doing iterative calculations over time, and the precision of the time values I want outputted over each loop pass can vary depending on my predefined parameters. Let's say I used this as my predefined time step:
tstep = 0.5 # seconds
So I would like outputted:
iteration 1: time = 0.0 s
iteration 2: time = 0.5 s
iteration 3: time = 1.0 s
And so on. But, let's say I switch my timestep:
tstep = 0.25 # seconds
Now I would want for following output:
iteration 1: time = 0.00 s
iteration 2: time = 0.25 s
iteration 3: time = 0.50 s
And so on. Here is what I would intuitively would think could work:
dec = len(str(tstep)[(str(tstep).find('.')+1):]) # Decimal places defined in tstep variable
t = 0.
count = 1
while t <= 5.:
print 'iteration %d: time = %.%d%f' % (count, dec, t)
t += tstep
count += 1
But this doesn't work. Does anyone have a possible solution to this? Possibly an alternate way of formatting that I'm just not considering? I prefer not to use %g
simply because the output isn't as clean. Thanks in advance!