How can I format a floating point number such that I limit the number of decimal places to a fixed length, but do not add padding zeros in the case when the number has less decimal places than asked for?
For printing with fixed precision, I would usually do the following:
print('{:.3f}'.format(123.4567)) # prints 123.457
However for number with less than 3 decimals, it adds padding zeros:
print('{:.3f}'.format(123.4)) # prints 123.400
What I would like is to have the second version keep the argument unchanged:
print('{:.3f}'.other_format(123.4)) # should print 123.4
What is a possible method to have the number printed as in the third example?
Thank you!
ginstead off, although, that might turn it into an exponential.result = '{:.3f}'.format(123.4)and.if '.' in result: result = result.rstrip("0")which is not pretty but might be more reliableroundfunction on the number prior to printing it.number = 124.4number = number.round(1)print(number)output: 124.4print_number = number.round(3)say, won't this always work for printing a number to 3 decimal places, removing zero padding? Granted, it might be very inefficient for the task at hand