The operator '%2.2f' will only execute the same number of decimal places, regardless of how many significant digits the number has. You will need to determine this number and manually change the format. You could shorten this by printing a line with a lot of decimal places and separating all trailing zeros.
The trivial function for this might look something like intel_format() in the example below:
import re foo_string = '%.10f' % (1.33333) bar_string = '%.10f' % (1) print 'Raw Output' print foo_string print bar_string print 'Strip trailing zeros' print re.split ('0+$', foo_string)[0] print re.split ('0+$', bar_string)[0] print 'Intelligently strip trailing zeros' def intel_format (nn): formatted = '%.10f' % (nn) stripped = re.split('0+$', formatted) if stripped[0][-1] == '.': return stripped[0] + '0' else: return stripped[0] print intel_format (1.3333) print intel_format (1.0)
When you start, you get this output:
Raw Output 1.3333300000 1.0000000000 Strip trailing zeros 1.33333 1. Intelligently strip trailing zeros 1.3333 1.0
ConcernedOfTunbridgeWells
source share